From fabca162a7029b4e051284590ec4e700f1b36a05 Mon Sep 17 00:00:00 2001 From: Luke Taylor Date: Sat, 24 Feb 2007 21:00:24 +0000 Subject: [PATCH] Added a customized checkstyle configuration file to tame the Maven 2 checkstyle report to the extent that it gives some useful infomation. Tidied up comments, excessively long lines, use of tabs etc. to match. --- acegi_checkstyle.xml | 205 ++++++++++++++++ .../acegisecurity/AccessDecisionManager.java | 6 +- .../acegisecurity/AfterInvocationManager.java | 10 +- .../org/acegisecurity/Authentication.java | 16 +- .../acegisecurity/AuthenticationManager.java | 2 +- .../AuthenticationTrustResolver.java | 4 +- .../org/acegisecurity/ConfigAttribute.java | 6 +- .../org/acegisecurity/GrantedAuthority.java | 4 +- .../acegisecurity/GrantedAuthorityImpl.java | 2 +- .../java/org/acegisecurity/RunAsManager.java | 12 +- .../java/org/acegisecurity/acl/AclEntry.java | 2 +- .../org/acegisecurity/acl/AclManager.java | 4 +- .../org/acegisecurity/acl/AclProvider.java | 8 +- .../acl/basic/AclObjectIdentity.java | 8 +- .../acl/basic/AclObjectIdentityAware.java | 4 +- .../acegisecurity/acl/basic/BasicAclDao.java | 6 +- .../acl/basic/BasicAclEntry.java | 22 +- .../acl/basic/BasicAclEntryCache.java | 8 +- .../acl/basic/BasicAclExtendedDao.java | 14 +- .../acl/basic/EffectiveAclsResolver.java | 6 +- ...GrantedAuthorityEffectiveAclsResolver.java | 5 +- .../acl/basic/SimpleAclEntry.java | 10 +- .../acl/basic/jdbc/JdbcDaoImpl.java | 23 +- .../acl/basic/jdbc/JdbcExtendedDaoImpl.java | 22 +- .../acls/AccessControlEntry.java | 31 +-- .../main/java/org/acegisecurity/acls/Acl.java | 65 ++--- .../acls/AclFormattingUtils.java | 7 +- .../org/acegisecurity/acls/AclService.java | 20 +- .../acls/AuditableAccessControlEntry.java | 16 +- .../org/acegisecurity/acls/AuditableAcl.java | 14 +- .../org/acegisecurity/acls/MutableAcl.java | 34 +-- .../acegisecurity/acls/MutableAclService.java | 16 +- .../org/acegisecurity/acls/OwnershipAcl.java | 22 +- .../org/acegisecurity/acls/Permission.java | 37 ++- .../acls/domain/AclAuthorizationStrategy.java | 10 +- .../domain/AclAuthorizationStrategyImpl.java | 5 +- .../acls/domain/AuditLogger.java | 14 +- .../acls/domain/BasePermission.java | 2 +- .../acls/domain/ConsoleAuditLogger.java | 4 +- .../org/acegisecurity/acls/jdbc/AclCache.java | 22 +- .../acls/jdbc/BasicLookupStrategy.java | 18 +- .../acls/jdbc/JdbcMutableAclService.java | 11 +- .../acls/jdbc/LookupStrategy.java | 12 +- .../acls/objectidentity/ObjectIdentity.java | 36 +-- .../objectidentity/ObjectIdentityImpl.java | 29 +-- .../ObjectIdentityRetrievalStrategy.java | 4 +- .../java/org/acegisecurity/acls/sid/Sid.java | 32 +-- .../acls/sid/SidRetrievalStrategy.java | 4 +- .../acegisecurity/adapters/AuthByAdapter.java | 4 +- .../adapters/PrincipalAcegiUserToken.java | 2 +- ...InvocationCollectionFilteringProvider.java | 10 +- .../AclEntryAfterInvocationProvider.java | 20 +- .../AfterInvocationProvider.java | 6 +- .../afterinvocation/ArrayFilterer.java | 9 +- ...InvocationCollectionFilteringProvider.java | 11 +- .../BasicAclEntryAfterInvocationProvider.java | 11 +- .../afterinvocation/Filterer.java | 8 +- .../captcha/CaptchaEntryPoint.java | 41 ++-- .../CaptchaValidationProcessingFilter.java | 12 +- .../ConcurrentSessionController.java | 4 +- .../ConcurrentSessionControllerImpl.java | 10 +- .../concurrent/SessionIdentifierAware.java | 4 +- .../concurrent/SessionRegistry.java | 12 +- .../concurrent/SessionRegistryUtils.java | 7 +- .../HttpSessionContextIntegrationFilter.java | 120 +++++---- .../context/SecurityContext.java | 6 +- .../SecurityContextHolderStrategy.java | 8 +- ...ationSimpleHttpInvokerRequestExecutor.java | 5 +- .../AuthorizationFailureEvent.java | 7 +- .../event/authorization/LoggerListener.java | 12 +- .../AbstractSecurityInterceptor.java | 20 +- .../intercept/ObjectDefinitionSource.java | 6 +- .../method/MethodDefinitionAttributes.java | 2 +- .../intercept/method/MethodDefinitionMap.java | 5 +- .../method/MethodDefinitionSourceEditor.java | 4 +- .../MethodDefinitionSourceAdvisor.java | 7 +- .../method/aspectj/AspectJCallback.java | 2 +- ...tractFilterInvocationDefinitionSource.java | 17 +- .../web/FilterInvocationDefinitionMap.java | 6 +- ...ilterInvocationDefinitionSourceEditor.java | 5 +- ...lterInvocationDefinitionSourceMapping.java | 13 +- .../ldap/DefaultInitialDirContextFactory.java | 26 +- .../org/acegisecurity/ldap/LdapCallback.java | 2 +- .../acegisecurity/ldap/LdapEntryMapper.java | 14 +- .../org/acegisecurity/ldap/LdapTemplate.java | 3 +- .../org/acegisecurity/ldap/LdapUtils.java | 7 +- .../search/FilterBasedLdapUserSearch.java | 2 +- .../providers/AuthenticationProvider.java | 19 +- .../providers/ProviderManager.java | 58 +++-- .../providers/TestingAuthenticationToken.java | 2 +- .../UsernamePasswordAuthenticationToken.java | 2 +- .../AnonymousAuthenticationToken.java | 2 +- .../providers/cas/CasAuthenticationToken.java | 2 +- .../cas/CasAuthoritiesPopulator.java | 14 +- .../providers/cas/CasProxyDecider.java | 23 +- .../providers/cas/StatelessTicketCache.java | 26 +- .../providers/cas/TicketValidator.java | 10 +- .../cas/proxy/RejectProxyTickets.java | 3 +- .../CasProxyTicketValidator.java | 16 +- ...ractUserDetailsAuthenticationProvider.java | 32 +-- .../dao/DaoAuthenticationProvider.java | 18 +- .../providers/dao/SaltSource.java | 2 +- .../providers/dao/UserCache.java | 8 +- .../MessageDigestPasswordEncoder.java | 26 +- .../providers/encoding/PasswordEncoder.java | 4 +- .../encoding/ShaPasswordEncoder.java | 17 +- .../providers/jaas/AuthorityGranter.java | 4 +- .../JaasAuthenticationCallbackHandler.java | 6 +- .../jaas/JaasAuthenticationProvider.java | 98 +++++--- .../jaas/JaasAuthenticationToken.java | 2 +- .../providers/jaas/JaasGrantedAuthority.java | 2 +- .../jaas/JaasPasswordCallbackHandler.java | 4 +- .../jaas/LoginExceptionResolver.java | 2 +- .../ldap/LdapAuthenticationProvider.java | 28 ++- .../ldap/authenticator/BindAuthenticator.java | 6 +- .../PasswordComparisonAuthenticator.java | 21 +- .../DefaultLdapAuthoritiesPopulator.java | 27 +- .../rcp/RemoteAuthenticationManager.java | 2 +- .../RememberMeAuthenticationToken.java | 2 +- .../x509/X509AuthenticationToken.java | 2 +- .../acegisecurity/runas/RunAsUserToken.java | 2 +- .../securechannel/ChannelDecisionManager.java | 6 +- .../securechannel/ChannelEntryPoint.java | 4 +- .../ChannelProcessingFilter.java | 4 +- .../securechannel/ChannelProcessor.java | 8 +- .../taglibs/authz/AccessControlListTag.java | 8 +- .../taglibs/authz/AuthenticationTag.java | 2 +- .../taglibs/authz/AuthorizeTag.java | 14 +- .../acegisecurity/taglibs/velocity/Authz.java | 14 +- .../ui/AbstractProcessingFilter.java | 12 +- .../acegisecurity/ui/AccessDeniedHandler.java | 2 +- .../ui/AccessDeniedHandlerImpl.java | 4 +- .../ui/AuthenticationDetailsSource.java | 2 +- .../ui/AuthenticationEntryPoint.java | 2 +- .../ui/logout/LogoutHandler.java | 6 +- .../logout/SecurityContextLogoutHandler.java | 52 ++-- .../RememberMeProcessingFilter.java | 6 +- .../ui/rememberme/RememberMeServices.java | 20 +- .../TokenBasedRememberMeServices.java | 75 +++--- .../ui/savedrequest/Enumerator.java | 8 +- .../ui/savedrequest/FastHttpDateFormat.java | 8 +- .../ui/savedrequest/SavedRequest.java | 6 +- .../ui/session/HttpSessionEventPublisher.java | 13 +- .../SwitchUserAuthorityChanger.java | 10 +- .../SwitchUserGrantedAuthority.java | 2 +- .../SwitchUserProcessingFilter.java | 12 +- ...eminderAuthenticationProcessingFilter.java | 14 +- .../ui/x509/X509ProcessingFilter.java | 9 +- .../org/acegisecurity/userdetails/User.java | 24 +- .../userdetails/UserDetails.java | 24 +- .../userdetails/UserDetailsService.java | 4 +- .../userdetails/jdbc/JdbcDaoImpl.java | 6 +- .../userdetails/ldap/LdapUserDetailsImpl.java | 6 +- .../ldap/LdapUserDetailsMapper.java | 7 +- .../acegisecurity/util/EncryptionUtils.java | 232 +++++++++--------- .../org/acegisecurity/util/FieldUtils.java | 7 +- .../acegisecurity/util/FilterChainProxy.java | 3 +- .../util/FilterInvocationUtils.java | 7 +- .../acegisecurity/util/FilterToBeanProxy.java | 10 +- .../acegisecurity/util/InMemoryResource.java | 8 +- .../util/MethodInvocationUtils.java | 7 +- .../org/acegisecurity/util/PortMapper.java | 4 +- .../org/acegisecurity/util/PortResolver.java | 4 +- .../acegisecurity/util/StringSplitUtils.java | 16 +- .../java/org/acegisecurity/util/UrlUtils.java | 9 +- .../vote/AccessDecisionVoter.java | 32 +-- .../org/acegisecurity/vote/AclEntryVoter.java | 4 +- .../vote/LabelBasedAclVoter.java | 121 ++++----- .../vote/LabelParameterStrategy.java | 4 +- .../org/acegisecurity/vote/LabeledData.java | 4 +- .../java/org/acegisecurity/ITargetObject.java | 10 +- .../acl/AclProviderManagerTests.java | 5 +- .../acegisecurity/ldap/LdapTestServer.java | 6 +- .../SwitchUserProcessingFilterTests.java | 20 +- .../util/EncryptionUtilsTests.java | 158 ++++++------ pom.xml | 3 + .../main/java/acegifier/WebXmlConverter.java | 12 +- .../java/acegifier/WebXmlConverterTests.java | 34 +-- .../java/sample/attributes/BankService.java | 18 +- .../main/java/sample/dms/AbstractElement.java | 134 +++++----- .../java/sample/dms/DataSourcePopulator.java | 194 +++++++-------- .../src/main/java/sample/dms/Directory.java | 28 +-- .../src/main/java/sample/dms/DocumentDao.java | 58 ++--- .../main/java/sample/dms/DocumentDaoImpl.java | 174 ++++++------- .../dms/src/main/java/sample/dms/File.java | 36 +-- .../secured/SecureDataSourcePopulator.java | 124 +++++----- .../dms/secured/SecureDocumentDaoImpl.java | 64 ++--- .../src/test/java/DmsIntegrationTests.java | 134 +++++----- .../test/java/SecureDmsIntegrationTests.java | 82 +++---- 189 files changed, 2207 insertions(+), 1789 deletions(-) create mode 100644 acegi_checkstyle.xml diff --git a/acegi_checkstyle.xml b/acegi_checkstyle.xml new file mode 100644 index 0000000000..f2a4bfb021 --- /dev/null +++ b/acegi_checkstyle.xml @@ -0,0 +1,205 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/src/main/java/org/acegisecurity/AccessDecisionManager.java b/core/src/main/java/org/acegisecurity/AccessDecisionManager.java index 7c7734f019..0b6b44c13c 100644 --- a/core/src/main/java/org/acegisecurity/AccessDecisionManager.java +++ b/core/src/main/java/org/acegisecurity/AccessDecisionManager.java @@ -36,7 +36,7 @@ public interface AccessDecisionManager { * @throws InsufficientAuthenticationException if access is denied as the authentication does not provide a * sufficient level of trust */ - public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config) + void decide(Authentication authentication, Object object, ConfigAttributeDefinition config) throws AccessDeniedException, InsufficientAuthenticationException; /** @@ -51,7 +51,7 @@ public interface AccessDecisionManager { * * @return true if this AccessDecisionManager can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); /** * Indicates whether the AccessDecisionManager implementation is able to provide access @@ -61,5 +61,5 @@ public interface AccessDecisionManager { * * @return true if the implementation can process the indicated class */ - public boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/acegisecurity/AfterInvocationManager.java b/core/src/main/java/org/acegisecurity/AfterInvocationManager.java index ef232336aa..313fd52e85 100644 --- a/core/src/main/java/org/acegisecurity/AfterInvocationManager.java +++ b/core/src/main/java/org/acegisecurity/AfterInvocationManager.java @@ -19,7 +19,7 @@ package org.acegisecurity; * Reviews the Object returned from a secure object invocation, * being able to modify the Object or throw an {@link * AccessDeniedException}. - * + * *

* Typically used to ensure the principal is permitted to access the domain * object instance returned by a service layer bean. Can also be used to @@ -28,7 +28,7 @@ package org.acegisecurity; * in conjunction with an {@link org.acegisecurity.acl.AclManager} to * obtain the access control list applicable for the domain object instance. *

- * + * *

* Special consideration should be given to using an * AfterInvocationManager on bean methods that modify a database. @@ -60,7 +60,7 @@ public interface AfterInvocationManager { * * @throws AccessDeniedException if access is denied */ - public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config, + Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config, Object returnedObject) throws AccessDeniedException; /** @@ -75,7 +75,7 @@ public interface AfterInvocationManager { * * @return true if this AfterInvocationManager can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); /** * Indicates whether the AfterInvocationManager implementation is able to provide access @@ -85,5 +85,5 @@ public interface AfterInvocationManager { * * @return true if the implementation can process the indicated class */ - public boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/acegisecurity/Authentication.java b/core/src/main/java/org/acegisecurity/Authentication.java index 9232de0798..8191ddeb48 100644 --- a/core/src/main/java/org/acegisecurity/Authentication.java +++ b/core/src/main/java/org/acegisecurity/Authentication.java @@ -22,12 +22,12 @@ import java.security.Principal; /** * Represents an authentication request. - * + * *

* An Authentication object is not considered authenticated until * it is processed by an {@link AuthenticationManager}. *

- * + * *

* Stored in a request {@link org.acegisecurity.context.SecurityContext}. *

@@ -46,7 +46,7 @@ public interface Authentication extends Principal, Serializable { * * @return the authorities granted to the principal, or null if authentication has not been completed */ - public GrantedAuthority[] getAuthorities(); + GrantedAuthority[] getAuthorities(); /** * The credentials that prove the principal is correct. This is usually a password, but could be anything @@ -54,7 +54,7 @@ public interface Authentication extends Principal, Serializable { * * @return the credentials that prove the identity of the Principal */ - public Object getCredentials(); + Object getCredentials(); /** * Stores additional details about the authentication request. These might be an IP address, certificate @@ -62,7 +62,7 @@ public interface Authentication extends Principal, Serializable { * * @return additional details about the authentication request, or null if not used */ - public Object getDetails(); + Object getDetails(); /** * The identity of the principal being authenticated. This is usually a username. Callers are expected to @@ -70,7 +70,7 @@ public interface Authentication extends Principal, Serializable { * * @return the Principal being authenticated */ - public Object getPrincipal(); + Object getPrincipal(); /** * Used to indicate to AbstractSecurityInterceptor whether it should present the @@ -85,7 +85,7 @@ public interface Authentication extends Principal, Serializable { * @return true if the token has been authenticated and the AbstractSecurityInterceptor does not need * to represent the token for re-authentication to the AuthenticationManager */ - public boolean isAuthenticated(); + boolean isAuthenticated(); /** * See {@link #isAuthenticated()} for a full description.

Implementations should always allow this @@ -101,6 +101,6 @@ public interface Authentication extends Principal, Serializable { * true as the argument) is rejected due to the implementation being immutable or * implementing its own alternative approach to {@link #isAuthenticated()} */ - public void setAuthenticated(boolean isAuthenticated) + void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException; } diff --git a/core/src/main/java/org/acegisecurity/AuthenticationManager.java b/core/src/main/java/org/acegisecurity/AuthenticationManager.java index e47f1f974b..64f7c7abd5 100644 --- a/core/src/main/java/org/acegisecurity/AuthenticationManager.java +++ b/core/src/main/java/org/acegisecurity/AuthenticationManager.java @@ -44,6 +44,6 @@ public interface AuthenticationManager { * * @throws AuthenticationException if authentication fails */ - public Authentication authenticate(Authentication authentication) + Authentication authenticate(Authentication authentication) throws AuthenticationException; } diff --git a/core/src/main/java/org/acegisecurity/AuthenticationTrustResolver.java b/core/src/main/java/org/acegisecurity/AuthenticationTrustResolver.java index 7272c429bc..20cb01e948 100644 --- a/core/src/main/java/org/acegisecurity/AuthenticationTrustResolver.java +++ b/core/src/main/java/org/acegisecurity/AuthenticationTrustResolver.java @@ -37,7 +37,7 @@ public interface AuthenticationTrustResolver { * @return true the passed authentication token represented an anonymous principal, false * otherwise */ - public boolean isAnonymous(Authentication authentication); + boolean isAnonymous(Authentication authentication); /** * Indicates whether the passed Authentication token represents user that has been remembered @@ -52,5 +52,5 @@ public interface AuthenticationTrustResolver { * @return true the passed authentication token represented a principal authenticated using a * remember-me token, false otherwise */ - public boolean isRememberMe(Authentication authentication); + boolean isRememberMe(Authentication authentication); } diff --git a/core/src/main/java/org/acegisecurity/ConfigAttribute.java b/core/src/main/java/org/acegisecurity/ConfigAttribute.java index 97af46423e..a168bac2b5 100644 --- a/core/src/main/java/org/acegisecurity/ConfigAttribute.java +++ b/core/src/main/java/org/acegisecurity/ConfigAttribute.java @@ -20,7 +20,7 @@ import java.io.Serializable; /** * Stores a security system related configuration attribute. - * + * *

* When an {@link org.acegisecurity.intercept.AbstractSecurityInterceptor} * is setup, a list of configuration attributes is defined for secure object @@ -28,7 +28,7 @@ import java.io.Serializable; * RunAsManager}, {@link AccessDecisionManager} or * AccessDecisionManager delegate. *

- * + * *

* Stored at runtime with other ConfigAttributes for the same * secure object target within a {@link ConfigAttributeDefinition}. @@ -52,5 +52,5 @@ public interface ConfigAttribute extends Serializable { * @return a representation of the configuration attribute (or null if the configuration attribute * cannot be expressed as a String with sufficient precision). */ - public String getAttribute(); + String getAttribute(); } diff --git a/core/src/main/java/org/acegisecurity/GrantedAuthority.java b/core/src/main/java/org/acegisecurity/GrantedAuthority.java index ac71992d5a..829a73fbb1 100644 --- a/core/src/main/java/org/acegisecurity/GrantedAuthority.java +++ b/core/src/main/java/org/acegisecurity/GrantedAuthority.java @@ -19,7 +19,7 @@ import java.io.Serializable; /** * Represents an authority granted to an {@link Authentication} object. - * + * *

* A GrantedAuthority must either represent itself as a * String or be specifically supported by an {@link @@ -44,5 +44,5 @@ public interface GrantedAuthority extends Serializable { * @return a representation of the granted authority (or null if the granted authority cannot be * expressed as a String with sufficient precision). */ - public String getAuthority(); + String getAuthority(); } diff --git a/core/src/main/java/org/acegisecurity/GrantedAuthorityImpl.java b/core/src/main/java/org/acegisecurity/GrantedAuthorityImpl.java index 8c2ff58870..c9a42681e6 100644 --- a/core/src/main/java/org/acegisecurity/GrantedAuthorityImpl.java +++ b/core/src/main/java/org/acegisecurity/GrantedAuthorityImpl.java @@ -28,7 +28,7 @@ import java.io.Serializable; public class GrantedAuthorityImpl implements GrantedAuthority, Serializable { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private String role; //~ Constructors =================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/RunAsManager.java b/core/src/main/java/org/acegisecurity/RunAsManager.java index 25493bc73e..6ace86ff9f 100644 --- a/core/src/main/java/org/acegisecurity/RunAsManager.java +++ b/core/src/main/java/org/acegisecurity/RunAsManager.java @@ -18,7 +18,7 @@ package org.acegisecurity; /** * Creates a new temporary {@link Authentication} object for the current secure * object invocation only. - * + * *

* This interface permits implementations to replace the * Authentication object that applies to the current secure @@ -29,7 +29,7 @@ package org.acegisecurity; * for the duration of the secure object callback only, returning it to * the original Authentication object when the callback ends. *

- * + * *

* This is provided so that systems with two layers of objects can be * established. One layer is public facing and has normal secure methods with @@ -43,7 +43,7 @@ package org.acegisecurity; * RunAsManager interface provides a mechanism to elevate * security in this manner. *

- * + * *

* It is expected implementations will provide a corresponding concrete * Authentication and AuthenticationProvider so that @@ -71,7 +71,7 @@ public interface RunAsManager { * @return a replacement object to be used for duration of the secure object invocation, or null if * the Authentication should be left as is */ - public Authentication buildRunAs(Authentication authentication, Object object, ConfigAttributeDefinition config); + Authentication buildRunAs(Authentication authentication, Object object, ConfigAttributeDefinition config); /** * Indicates whether this RunAsManager is able to process the passed @@ -84,7 +84,7 @@ public interface RunAsManager { * * @return true if this RunAsManager can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); /** * Indicates whether the RunAsManager implementation is able to provide run-as replacement for @@ -94,5 +94,5 @@ public interface RunAsManager { * * @return true if the implementation can process the indicated class */ - public boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/acegisecurity/acl/AclEntry.java b/core/src/main/java/org/acegisecurity/acl/AclEntry.java index a7fbed083b..48fe989951 100644 --- a/core/src/main/java/org/acegisecurity/acl/AclEntry.java +++ b/core/src/main/java/org/acegisecurity/acl/AclEntry.java @@ -21,7 +21,7 @@ import java.io.Serializable; /** * Marker interface representing an access control list entry associated with a * specific domain object instance. - * + * * @author Ben Alex * @version $Id$ */ diff --git a/core/src/main/java/org/acegisecurity/acl/AclManager.java b/core/src/main/java/org/acegisecurity/acl/AclManager.java index d259ae684e..fc82de485c 100644 --- a/core/src/main/java/org/acegisecurity/acl/AclManager.java +++ b/core/src/main/java/org/acegisecurity/acl/AclManager.java @@ -35,7 +35,7 @@ public interface AclManager { * * @return the ACLs that apply, or null if no ACLs apply to the specified domain instance */ - public AclEntry[] getAcls(Object domainInstance); + AclEntry[] getAcls(Object domainInstance); /** * Obtains the ACLs that apply to the specified domain instance, but only including those ACLs which have @@ -47,5 +47,5 @@ public interface AclManager { * @return only those ACLs applying to the domain instance that have been granted to the principal (or * null) if no such ACLs are found */ - public AclEntry[] getAcls(Object domainInstance, Authentication authentication); + AclEntry[] getAcls(Object domainInstance, Authentication authentication); } diff --git a/core/src/main/java/org/acegisecurity/acl/AclProvider.java b/core/src/main/java/org/acegisecurity/acl/AclProvider.java index 635957cee1..0ccf9e264b 100644 --- a/core/src/main/java/org/acegisecurity/acl/AclProvider.java +++ b/core/src/main/java/org/acegisecurity/acl/AclProvider.java @@ -21,7 +21,7 @@ import org.acegisecurity.Authentication; /** * Indicates a class can process a given domain object instance and * authoritatively return the ACLs that apply. - * + * *

* Implementations are typically called from the {@link AclProviderManager}. *

@@ -40,7 +40,7 @@ public interface AclProvider { * * @return the ACLs that apply, or null if no ACLs apply to the specified domain instance */ - public AclEntry[] getAcls(Object domainInstance); + AclEntry[] getAcls(Object domainInstance); /** * Obtains the ACLs that apply to the specified domain instance and presented Authentication @@ -52,7 +52,7 @@ public interface AclProvider { * @return only those ACLs applying to the domain instance that have been granted to the principal (or * null) if no such ACLs are found */ - public AclEntry[] getAcls(Object domainInstance, Authentication authentication); + AclEntry[] getAcls(Object domainInstance, Authentication authentication); /** * Indicates whether this AclProvider can authoritatively return ACL information for the @@ -63,5 +63,5 @@ public interface AclProvider { * @return true if this provider is authoritative for the specified domain object instance, * false otherwise */ - public boolean supports(Object domainInstance); + boolean supports(Object domainInstance); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentity.java b/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentity.java index 5ba4f97f10..b7c144b367 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentity.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentity.java @@ -20,7 +20,7 @@ import java.io.Serializable; /** * Interface representing the identity of an individual domain object instance. - * + * *

* It should be noted that AclObjectIdentity instances are created * in various locations throughout the package. As @@ -31,7 +31,7 @@ import java.io.Serializable; * identity1.equals(identity2), rather than reference-equality of * identity1==identity2. *

- * + * *

* In practical terms this means you must implement the standard * java.lang.Object methods shown below. Depending on your @@ -53,12 +53,12 @@ public interface AclObjectIdentity extends Serializable { * * @return true if the objects are equal, false otherwise */ - public boolean equals(Object obj); + boolean equals(Object obj); /** * Refer to the java.lang.Object documentation for the interface contract. * * @return a hash code representation of this object */ - public int hashCode(); + int hashCode(); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentityAware.java b/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentityAware.java index bfe7b2940b..931bcab7b2 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentityAware.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/AclObjectIdentityAware.java @@ -18,7 +18,7 @@ package org.acegisecurity.acl.basic; /** * Indicates a domain object instance is able to provide {@link * AclObjectIdentity} information. - * + * *

* Domain objects must implement this interface if they wish to provide an * AclObjectIdentity rather than it being determined by relying @@ -37,5 +37,5 @@ public interface AclObjectIdentityAware { * * @return the ACL object identity for this instance (can never be null) */ - public AclObjectIdentity getAclObjectIdentity(); + AclObjectIdentity getAclObjectIdentity(); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclDao.java b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclDao.java index fa5f979846..015a88e94a 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclDao.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclDao.java @@ -18,13 +18,13 @@ package org.acegisecurity.acl.basic; /** * Represents a data access object that can return the {@link BasicAclEntry}s * applying to a given ACL object identity. - * + * *

* BasicAclDao implementations are responsible for interpreting a * given {@link AclObjectIdentity} and being able to lookup and return the * corresponding {@link BasicAclEntry}[]s. *

- * + * *

* BasicAclDaos many, but are not required to, allow the backend * ACL repository to specify the class of BasicAclEntry @@ -48,5 +48,5 @@ public interface BasicAclDao { * @return the ACLs that apply (no nulls are permitted in the array), or null if no ACLs * could be found for the specified ACL object identity */ - public BasicAclEntry[] getAcls(AclObjectIdentity aclObjectIdentity); + BasicAclEntry[] getAcls(AclObjectIdentity aclObjectIdentity); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntry.java b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntry.java index 7a7968c921..ce1fe2bf49 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntry.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntry.java @@ -35,7 +35,7 @@ public interface BasicAclEntry extends AclEntry { * * @return the ACL object identity that is subject of this ACL entry (never null) */ - public AclObjectIdentity getAclObjectIdentity(); + AclObjectIdentity getAclObjectIdentity(); /** * Indicates any ACL parent of the domain object instance. This is used by BasicAclProvider to @@ -44,7 +44,7 @@ public interface BasicAclEntry extends AclEntry { * @return the ACL object identity that is the parent of this ACL entry (may be null if no parent * should be consulted) */ - public AclObjectIdentity getAclObjectParentIdentity(); + AclObjectIdentity getAclObjectParentIdentity(); /** * Access control lists in this package are based on bit masking. The integer value of the bit mask can be @@ -53,7 +53,7 @@ public interface BasicAclEntry extends AclEntry { * @return the bit mask applicable to this ACL entry (zero indicates a bit mask where no permissions have been * granted) */ - public int getMask(); + int getMask(); /** * A domain object instance will usually have multiple BasicAclEntrys. Each separate @@ -65,12 +65,12 @@ public interface BasicAclEntry extends AclEntry { * object type will vary depending on the type of recipient. For instance, it might be a String * containing a username, or a GrantedAuthorityImpl containing a complex granted authority that is * being granted the permissions contained in this access control entry. The {@link EffectiveAclsResolver} and - * {@link BasicAclProvider#getAcls(Object, Authentication)} can process the different recipient types and return - * only those that apply to a specified Authentication object.

+ * {@link BasicAclProvider#getAcls(Object,org.acegisecurity.Authentication)} can process the different recipient + * types and return only those that apply to a specified Authentication object.

* * @return the recipient of this access control list entry (never null) */ - public Object getRecipient(); + Object getRecipient(); /** * Determine if the mask of this entry includes this permission or not @@ -79,7 +79,7 @@ public interface BasicAclEntry extends AclEntry { * * @return if the entry's mask includes this permission */ - public boolean isPermitted(int permissionToCheck); + boolean isPermitted(int permissionToCheck); /** * This setter should only be used by DAO implementations. @@ -87,7 +87,7 @@ public interface BasicAclEntry extends AclEntry { * @param aclObjectIdentity an object which can be used to uniquely identify the domain object instance subject of * this ACL entry */ - public void setAclObjectIdentity(AclObjectIdentity aclObjectIdentity); + void setAclObjectIdentity(AclObjectIdentity aclObjectIdentity); /** * This setter should only be used by DAO implementations. @@ -96,14 +96,14 @@ public interface BasicAclEntry extends AclEntry { * this ACL entry, or null if either the domain object instance has no parent or its parent * should be not used to compute an inheritance hierarchy */ - public void setAclObjectParentIdentity(AclObjectIdentity aclObjectParentIdentity); + void setAclObjectParentIdentity(AclObjectIdentity aclObjectParentIdentity); /** * This setter should only be used by DAO implementations. * * @param mask the integer representing the permissions bit mask */ - public void setMask(int mask); + void setMask(int mask); /** * This setter should only be used by DAO implementations. @@ -111,5 +111,5 @@ public interface BasicAclEntry extends AclEntry { * @param recipient a representation of the recipient of this ACL entry that makes sense to an * EffectiveAclsResolver implementation */ - public void setRecipient(Object recipient); + void setRecipient(Object recipient); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntryCache.java b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntryCache.java index 2bdd862b32..7edcc19815 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntryCache.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclEntryCache.java @@ -17,7 +17,7 @@ package org.acegisecurity.acl.basic; /** * Provides a cache of {@link BasicAclEntry} objects. - * + * *

* Implementations should provide appropriate methods to set their cache * parameters (eg time-to-live) and/or force removal of entities before their @@ -41,7 +41,7 @@ public interface BasicAclEntryCache { * @return any applicable BasicAclEntrys (no nulls are permitted in the returned array) * or null if the object identity could not be found or if the cache entry has expired */ - public BasicAclEntry[] getEntriesFromCache(AclObjectIdentity aclObjectIdentity); + BasicAclEntry[] getEntriesFromCache(AclObjectIdentity aclObjectIdentity); /** * Places an array of {@link BasicAclEntry}s in the cache.

No nulls are allowed in the @@ -50,12 +50,12 @@ public interface BasicAclEntryCache { * @param basicAclEntry the ACL entries to cache (the key will be extracted from the {@link * BasicAclEntry#getAclObjectIdentity()} method */ - public void putEntriesInCache(BasicAclEntry[] basicAclEntry); + void putEntriesInCache(BasicAclEntry[] basicAclEntry); /** * Removes all ACL entries related to an {@link AclObjectIdentity} from the cache. * * @param aclObjectIdentity which should be removed from the cache */ - public void removeEntriesFromCache(AclObjectIdentity aclObjectIdentity); + void removeEntriesFromCache(AclObjectIdentity aclObjectIdentity); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclExtendedDao.java b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclExtendedDao.java index 218a7ada98..e494449cdb 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/BasicAclExtendedDao.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/BasicAclExtendedDao.java @@ -21,12 +21,12 @@ import org.springframework.dao.DataAccessException; /** * Represents a more extensive data access object * for {@link BasicAclEntry}s. - * - *

+ * + *

* BasicAclExtendedDao implementations are responsible for interpreting a * a given {@link AclObjectIdentity}. *

- * + * * @author Ben Alex * @version $Id$ */ @@ -43,10 +43,10 @@ public interface BasicAclExtendedDao extends BasicAclDao { * * @throws DataAccessException DOCUMENT ME! */ - public void changeMask(AclObjectIdentity aclObjectIdentity, Object recipient, Integer newMask) + void changeMask(AclObjectIdentity aclObjectIdentity, Object recipient, Integer newMask) throws DataAccessException; - public void create(BasicAclEntry basicAclEntry) throws DataAccessException; + void create(BasicAclEntry basicAclEntry) throws DataAccessException; /** * Deletes all entries associated with the specified AclObjectIdentity. @@ -55,7 +55,7 @@ public interface BasicAclExtendedDao extends BasicAclDao { * * @throws DataAccessException DOCUMENT ME! */ - public void delete(AclObjectIdentity aclObjectIdentity) + void delete(AclObjectIdentity aclObjectIdentity) throws DataAccessException; /** @@ -67,6 +67,6 @@ public interface BasicAclExtendedDao extends BasicAclDao { * * @throws DataAccessException DOCUMENT ME! */ - public void delete(AclObjectIdentity aclObjectIdentity, Object recipient) + void delete(AclObjectIdentity aclObjectIdentity, Object recipient) throws DataAccessException; } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/EffectiveAclsResolver.java b/core/src/main/java/org/acegisecurity/acl/basic/EffectiveAclsResolver.java index 6e51e18909..d1a76534c1 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/EffectiveAclsResolver.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/EffectiveAclsResolver.java @@ -23,14 +23,14 @@ import org.acegisecurity.acl.AclEntry; /** * Determines the ACLs that are effective for a given * Authentication object. - * + * *

* Implementations will vary depending on their ability to interpret the * "recipient" object types contained in {@link BasicAclEntry} instances, and * how those recipient object types correspond to * Authentication-presented principals and granted authorities. *

- * + * *

* Implementations should not filter the resulting ACL list from lower-order * permissions. So if a resulting ACL list grants a "read" permission, an @@ -57,5 +57,5 @@ public interface EffectiveAclsResolver { * * @return the ACLs that apply to the presented principal, or null if there are none after filtering */ - public AclEntry[] resolveEffectiveAcls(AclEntry[] allAcls, Authentication filteredBy); + AclEntry[] resolveEffectiveAcls(AclEntry[] allAcls, Authentication filteredBy); } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/GrantedAuthorityEffectiveAclsResolver.java b/core/src/main/java/org/acegisecurity/acl/basic/GrantedAuthorityEffectiveAclsResolver.java index 999964f98c..d2fc33939a 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/GrantedAuthorityEffectiveAclsResolver.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/GrantedAuthorityEffectiveAclsResolver.java @@ -96,9 +96,8 @@ public class GrantedAuthorityEffectiveAclsResolver implements EffectiveAclsResol if ((authorities == null) || (authorities.length == 0)) { if (logger.isDebugEnabled()) { - logger.debug( - "Did not match principal and there are no granted authorities, so cannot compare with recipient: " - + recipient); + logger.debug("Did not match principal and there are no granted authorities, " + + "so cannot compare with recipient: " + recipient); } continue; diff --git a/core/src/main/java/org/acegisecurity/acl/basic/SimpleAclEntry.java b/core/src/main/java/org/acegisecurity/acl/basic/SimpleAclEntry.java index 51740d8514..818525d288 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/SimpleAclEntry.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/SimpleAclEntry.java @@ -50,15 +50,15 @@ public class SimpleAclEntry extends AbstractBasicAclEntry { }; private static final String[] VALID_PERMISSIONS_AS_STRING = { - "NOTHING", "ADMINISTRATION", "READ", "WRITE", "CREATE", "DELETE", "READ_WRITE_CREATE_DELETE", "READ_WRITE_CREATE", - "READ_WRITE", "READ_WRITE_DELETE" }; + "NOTHING", "ADMINISTRATION", "READ", "WRITE", "CREATE", "DELETE", "READ_WRITE_CREATE_DELETE", + "READ_WRITE_CREATE", "READ_WRITE", "READ_WRITE_DELETE" }; //~ Constructors =================================================================================================== /** * Allows {@link BasicAclDao} implementations to construct this object * using newInstance(). - * + * *

* Normal classes should not use this default constructor. *

@@ -119,7 +119,7 @@ public class SimpleAclEntry extends AbstractBasicAclEntry { /** * Parse a permission {@link String} literal and return associated value. - * + * * @param permission one of the field names that represent a permission: ADMINISTRATION, * READ, WRITE,... * @return the value associated to that permission @@ -136,7 +136,7 @@ public class SimpleAclEntry extends AbstractBasicAclEntry { /** * Parse a list of permission {@link String} literals and return associated values. - * + * * @param permissions array with permissions as {@link String} * @see #parsePermission(String) for valid values */ diff --git a/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcDaoImpl.java b/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcDaoImpl.java index 5095c1227c..4dd5cb6ac5 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcDaoImpl.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcDaoImpl.java @@ -42,17 +42,27 @@ import javax.sql.DataSource; /** - *

Retrieves ACL details from a JDBC location.

- *

A default database structure is assumed. This may be overridden by setting the default query strings to use. + * Retrieves ACL details from a JDBC location. + *

+ * A default database structure is assumed. This may be overridden by setting the default query strings to use. * If this does not provide enough flexibility, another strategy would be to subclass this class and override the - * {@link MappingSqlQuery} instance used, via the {@link #initMappingSqlQueries()} extension point.

+ * {@link MappingSqlQuery} instance used, via the {@link #initMappingSqlQueries()} extension point. + *

*/ public class JdbcDaoImpl extends JdbcDaoSupport implements BasicAclDao { //~ Static fields/initializers ===================================================================================== public static final String RECIPIENT_USED_FOR_INHERITENCE_MARKER = "___INHERITENCE_MARKER_ONLY___"; - public static final String DEF_ACLS_BY_OBJECT_IDENTITY_QUERY = "SELECT RECIPIENT, MASK FROM acl_permission WHERE acl_object_identity = ?"; - public static final String DEF_OBJECT_PROPERTIES_QUERY = "SELECT CHILD.ID, CHILD.OBJECT_IDENTITY, CHILD.ACL_CLASS, PARENT.OBJECT_IDENTITY as PARENT_OBJECT_IDENTITY FROM acl_object_identity as CHILD LEFT OUTER JOIN acl_object_identity as PARENT ON CHILD.parent_object=PARENT.id WHERE CHILD.object_identity = ?"; + public static final String DEF_ACLS_BY_OBJECT_IDENTITY_QUERY = + "SELECT RECIPIENT, MASK FROM acl_permission WHERE acl_object_identity = ?"; + public static final String DEF_OBJECT_PROPERTIES_QUERY = + "SELECT CHILD.ID, " + + "CHILD.OBJECT_IDENTITY, " + + "CHILD.ACL_CLASS, " + + "PARENT.OBJECT_IDENTITY as PARENT_OBJECT_IDENTITY " + + "FROM acl_object_identity as CHILD " + + "LEFT OUTER JOIN acl_object_identity as PARENT ON CHILD.parent_object=PARENT.id " + + "WHERE CHILD.object_identity = ?"; private static final Log logger = LogFactory.getLog(JdbcDaoImpl.class); //~ Instance fields ================================================================================================ @@ -382,7 +392,8 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements BasicAclDao { throw new IllegalArgumentException(cnf.getMessage()); } - return new AclDetailsHolder(id, buildIdentity(objectIdentity), buildIdentity(parentObjectIdentity), aclClazz); + return new AclDetailsHolder(id, + buildIdentity(objectIdentity), buildIdentity(parentObjectIdentity), aclClazz); } } } diff --git a/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcExtendedDaoImpl.java b/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcExtendedDaoImpl.java index 219cf44465..7311262ef2 100644 --- a/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcExtendedDaoImpl.java +++ b/core/src/main/java/org/acegisecurity/acl/basic/jdbc/JdbcExtendedDaoImpl.java @@ -48,8 +48,8 @@ import javax.sql.DataSource; /** *

Extension of the base {@link JdbcDaoImpl}, which implements {@link BasicAclExtendedDao}.

- *

A default database structure is assumed. This may be overridden by setting the default query strings to use.

- *

If you are using a cache with BasicAclProvider, you should specify that cache via {@link + *

A default database structure is assumed. This may be overridden by setting the default query strings to use.

+ *

If you are using a cache with BasicAclProvider, you should specify that cache via {@link * #setBasicAclEntryCache(BasicAclEntryCache)}. This will cause cache evictions (removals) to take place whenever a * DAO mutator method is called.

*

This implementation works with String based recipients and {@link @@ -63,12 +63,18 @@ public class JdbcExtendedDaoImpl extends JdbcDaoImpl implements BasicAclExtended //~ Static fields/initializers ===================================================================================== private static final Log logger = LogFactory.getLog(JdbcExtendedDaoImpl.class); - public static final String DEF_ACL_OBJECT_IDENTITY_DELETE_STATEMENT = "DELETE FROM acl_object_identity WHERE id = ?"; - public static final String DEF_ACL_OBJECT_IDENTITY_INSERT_STATEMENT = "INSERT INTO acl_object_identity (object_identity, parent_object, acl_class) VALUES (?, ?, ?)"; - public static final String DEF_ACL_PERMISSION_DELETE_STATEMENT = "DELETE FROM acl_permission WHERE acl_object_identity = ? AND recipient = ?"; - public static final String DEF_ACL_PERMISSION_INSERT_STATEMENT = "INSERT INTO acl_permission (acl_object_identity, recipient, mask) VALUES (?, ?, ?)"; - public static final String DEF_ACL_PERMISSION_UPDATE_STATEMENT = "UPDATE acl_permission SET mask = ? WHERE id = ?"; - public static final String DEF_LOOKUP_PERMISSION_ID_QUERY = "SELECT id FROM acl_permission WHERE acl_object_identity = ? AND recipient = ?"; + public static final String DEF_ACL_OBJECT_IDENTITY_DELETE_STATEMENT = + "DELETE FROM acl_object_identity WHERE id = ?"; + public static final String DEF_ACL_OBJECT_IDENTITY_INSERT_STATEMENT = + "INSERT INTO acl_object_identity (object_identity, parent_object, acl_class) VALUES (?, ?, ?)"; + public static final String DEF_ACL_PERMISSION_DELETE_STATEMENT = + "DELETE FROM acl_permission WHERE acl_object_identity = ? AND recipient = ?"; + public static final String DEF_ACL_PERMISSION_INSERT_STATEMENT = + "INSERT INTO acl_permission (acl_object_identity, recipient, mask) VALUES (?, ?, ?)"; + public static final String DEF_ACL_PERMISSION_UPDATE_STATEMENT = + "UPDATE acl_permission SET mask = ? WHERE id = ?"; + public static final String DEF_LOOKUP_PERMISSION_ID_QUERY = + "SELECT id FROM acl_permission WHERE acl_object_identity = ? AND recipient = ?"; //~ Instance fields ================================================================================================ diff --git a/core/src/main/java/org/acegisecurity/acls/AccessControlEntry.java b/core/src/main/java/org/acegisecurity/acls/AccessControlEntry.java index 61ef097fdb..a5df1648d5 100644 --- a/core/src/main/java/org/acegisecurity/acls/AccessControlEntry.java +++ b/core/src/main/java/org/acegisecurity/acls/AccessControlEntry.java @@ -19,32 +19,33 @@ import org.acegisecurity.acls.sid.Sid; import java.io.Serializable; -/** - * Represents an individual permission assignment within an {@link Acl}. - * - *

- * Instances MUST be immutable, as they are returned by Acl - * and should not allow client modification. - * - * @author Ben Alex - * @version $Id$ - * +/** + * Represents an individual permission assignment within an {@link Acl}. + * + *

+ * Instances MUST be immutable, as they are returned by Acl + * and should not allow client modification. + *

+ * + * @author Ben Alex + * @version $Id$ + * */ public interface AccessControlEntry { //~ Methods ======================================================================================================== - public Acl getAcl(); + Acl getAcl(); /** * Obtains an identifier that represents this ACE. * * @return the identifier, or null if unsaved */ - public Serializable getId(); + Serializable getId(); - public Permission getPermission(); + Permission getPermission(); - public Sid getSid(); + Sid getSid(); /** * Indicates the a Permission is being granted to the relevant Sid. If false, indicates the permission is @@ -52,5 +53,5 @@ public interface AccessControlEntry { * * @return true if being granted, false otherwise */ - public boolean isGranting(); + boolean isGranting(); } diff --git a/core/src/main/java/org/acegisecurity/acls/Acl.java b/core/src/main/java/org/acegisecurity/acls/Acl.java index 546f9f898e..adf8a4a3e1 100644 --- a/core/src/main/java/org/acegisecurity/acls/Acl.java +++ b/core/src/main/java/org/acegisecurity/acls/Acl.java @@ -20,25 +20,25 @@ import org.acegisecurity.acls.sid.Sid; import java.io.Serializable; -/** - * Represents an access control list (ACL) for a domain object. - * - *

- * An Acl represents all ACL entries for a given domain object. In - * order to avoid needing references to the domain object itself, this - * interface handles indirection between a domain object and an ACL object - * identity via the {@link - * org.acegisecurity.acls.objectidentity.ObjectIdentity} interface. - *

- * - *

- * An implementation represents the {@link org.acegisecurity.acls.Permission} - * list applicable for some or all {@link org.acegisecurity.acls.sid.Sid} - * instances. - *

- * - * @author Ben Alex - * @version $Id$ +/** + * Represents an access control list (ACL) for a domain object. + * + *

+ * An Acl represents all ACL entries for a given domain object. In + * order to avoid needing references to the domain object itself, this + * interface handles indirection between a domain object and an ACL object + * identity via the {@link + * org.acegisecurity.acls.objectidentity.ObjectIdentity} interface. + *

+ * + *

+ * An implementation represents the {@link org.acegisecurity.acls.Permission} + * list applicable for some or all {@link org.acegisecurity.acls.sid.Sid} + * instances. + *

+ * + * @author Ben Alex + * @version $Id$ */ public interface Acl extends Serializable { //~ Methods ======================================================================================================== @@ -50,14 +50,14 @@ public interface Acl extends Serializable { * particular ordering logic in authorization decisions, the entries returned by this method MUST be * ordered in that manner.

*

Do NOT use this method for making authorization decisions. Instead use {@link - * #isGranted(Permission[], Sid[])}.

+ * #isGranted(Permission[], Sid[], boolean)}.

*

This method must operate correctly even if the Acl only represents a subset of * Sids. The caller is responsible for correctly handling the result if only a subset of * Sids is represented.

* * @return the list of entries represented by the Acl */ - public AccessControlEntry[] getEntries(); + AccessControlEntry[] getEntries(); /** * Obtains the domain object this Acl provides entries for. This is immutable once an @@ -65,7 +65,7 @@ public interface Acl extends Serializable { * * @return the object identity */ - public ObjectIdentity getObjectIdentity(); + ObjectIdentity getObjectIdentity(); /** * Determines the owner of the Acl. The meaning of ownership varies by implementation and is @@ -73,7 +73,7 @@ public interface Acl extends Serializable { * * @return the owner (may be null if the implementation does not use ownership concepts) */ - public Sid getOwner(); + Sid getOwner(); /** * A domain object may have a parent for the purpose of ACL inheritance. If there is a parent, its ACL can @@ -87,7 +87,7 @@ public interface Acl extends Serializable { * * @return the parent Acl */ - public Acl getParentAcl(); + Acl getParentAcl(); /** * Indicates whether the ACL entries from the {@link #getParentAcl()} should flow down into the current @@ -98,7 +98,7 @@ public interface Acl extends Serializable { * * @return true if parent ACL entries inherit into the current Acl */ - public boolean isEntriesInheriting(); + boolean isEntriesInheriting(); /** * This is the actual authorization logic method, and must be used whenever ACL authorization decisions are @@ -131,22 +131,25 @@ public interface Acl extends Serializable { * @throws UnloadedSidException thrown if the Acl does not have details for one or more of the * Sids passed as arguments */ - public boolean isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode) + boolean isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode) throws NotFoundException, UnloadedSidException; /** * For efficiency reasons an Acl may be loaded and not contain entries for every * Sid in the system. If an Acl has been loaded and does not represent every * Sid, all methods of the Sid can only be used within the limited scope of the - * Sid instances it actually represents.

It is normal to load an Acl for only - * particular Sids if read-only authorization decisions are being made. However, if user interface - * reporting or modification of Acls are desired, an Acl should be loaded with all - * Sids. This method denotes whether or not the specified Sids have been loaded or not.

+ * Sid instances it actually represents. + *

+ * It is normal to load an Acl for only particular Sids if read-only authorization + * decisions are being made. However, if user interface reporting or modification of Acls are + * desired, an Acl should be loaded with all Sids. This method denotes whether or + * not the specified Sids have been loaded or not. + *

* * @param sids one or more security identities the caller is interest in knowing whether this Sid * supports * * @return true if every passed Sid is represented by this Acl instance */ - public boolean isSidLoaded(Sid[] sids); + boolean isSidLoaded(Sid[] sids); } diff --git a/core/src/main/java/org/acegisecurity/acls/AclFormattingUtils.java b/core/src/main/java/org/acegisecurity/acls/AclFormattingUtils.java index f846c6619b..e6f309ffea 100644 --- a/core/src/main/java/org/acegisecurity/acls/AclFormattingUtils.java +++ b/core/src/main/java/org/acegisecurity/acls/AclFormattingUtils.java @@ -23,7 +23,12 @@ import org.springframework.util.Assert; * @author Ben Alex * @version $Id$ */ -public class AclFormattingUtils { +public final class AclFormattingUtils { + //~ Constructors =================================================================================================== + + private AclFormattingUtils() { + } + //~ Methods ======================================================================================================== public static String demergePatterns(String original, String removeBits) { diff --git a/core/src/main/java/org/acegisecurity/acls/AclService.java b/core/src/main/java/org/acegisecurity/acls/AclService.java index d3d0c3dd07..fa0e90af91 100644 --- a/core/src/main/java/org/acegisecurity/acls/AclService.java +++ b/core/src/main/java/org/acegisecurity/acls/AclService.java @@ -20,11 +20,11 @@ import org.acegisecurity.acls.sid.Sid; import java.util.Map; -/** - * Provides retrieval of {@link Acl} instances. - * - * @author Ben Alex - * @version $Id$ +/** + * Provides retrieval of {@link Acl} instances. + * + * @author Ben Alex + * @version $Id$ */ public interface AclService { //~ Methods ======================================================================================================== @@ -36,7 +36,7 @@ public interface AclService { * * @return the children (or null if none were found) */ - public ObjectIdentity[] findChildren(ObjectIdentity parentIdentity); + ObjectIdentity[] findChildren(ObjectIdentity parentIdentity); /** * Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.

This method @@ -49,7 +49,7 @@ public interface AclService { * * @throws NotFoundException DOCUMENT ME! */ - public Acl readAclById(ObjectIdentity object) throws NotFoundException; + Acl readAclById(ObjectIdentity object) throws NotFoundException; /** * Same as {@link #readAclsById(ObjectIdentity[], Sid[])} except it returns only a single Acl. @@ -61,7 +61,7 @@ public interface AclService { * * @throws NotFoundException DOCUMENT ME! */ - public Acl readAclById(ObjectIdentity object, Sid[] sids) + Acl readAclById(ObjectIdentity object, Sid[] sids) throws NotFoundException; /** @@ -75,7 +75,7 @@ public interface AclService { * * @throws NotFoundException DOCUMENT ME! */ - public Map readAclsById(ObjectIdentity[] objects) throws NotFoundException; + Map readAclsById(ObjectIdentity[] objects) throws NotFoundException; /** * Obtains all the Acls that apply for the passed Objects, but only for the @@ -95,6 +95,6 @@ public interface AclService { * * @throws NotFoundException DOCUMENT ME! */ - public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) + Map readAclsById(ObjectIdentity[] objects, Sid[] sids) throws NotFoundException; } diff --git a/core/src/main/java/org/acegisecurity/acls/AuditableAccessControlEntry.java b/core/src/main/java/org/acegisecurity/acls/AuditableAccessControlEntry.java index 3fcda04325..d138a0c2d7 100644 --- a/core/src/main/java/org/acegisecurity/acls/AuditableAccessControlEntry.java +++ b/core/src/main/java/org/acegisecurity/acls/AuditableAccessControlEntry.java @@ -14,17 +14,17 @@ */ package org.acegisecurity.acls; -/** - * Represents an ACE that provides auditing information. - * - * @author Ben Alex - * @version $Id$ - * +/** + * Represents an ACE that provides auditing information. + * + * @author Ben Alex + * @version $Id$ + * */ public interface AuditableAccessControlEntry extends AccessControlEntry { //~ Methods ======================================================================================================== - public boolean isAuditFailure(); + boolean isAuditFailure(); - public boolean isAuditSuccess(); + boolean isAuditSuccess(); } diff --git a/core/src/main/java/org/acegisecurity/acls/AuditableAcl.java b/core/src/main/java/org/acegisecurity/acls/AuditableAcl.java index cb5c4ecfa9..85ae0d8dd7 100644 --- a/core/src/main/java/org/acegisecurity/acls/AuditableAcl.java +++ b/core/src/main/java/org/acegisecurity/acls/AuditableAcl.java @@ -17,15 +17,15 @@ package org.acegisecurity.acls; import java.io.Serializable; -/** - * A mutable ACL that provides audit capabilities. - * - * @author Ben Alex - * @version $Id$ - * +/** + * A mutable ACL that provides audit capabilities. + * + * @author Ben Alex + * @version $Id$ + * */ public interface AuditableAcl extends MutableAcl { //~ Methods ======================================================================================================== - public void updateAuditing(Serializable aceId, boolean auditSuccess, boolean auditFailure); + void updateAuditing(Serializable aceId, boolean auditSuccess, boolean auditFailure); } diff --git a/core/src/main/java/org/acegisecurity/acls/MutableAcl.java b/core/src/main/java/org/acegisecurity/acls/MutableAcl.java index 8bcd8ab45a..394de6230d 100644 --- a/core/src/main/java/org/acegisecurity/acls/MutableAcl.java +++ b/core/src/main/java/org/acegisecurity/acls/MutableAcl.java @@ -19,21 +19,21 @@ import org.acegisecurity.acls.sid.Sid; import java.io.Serializable; -/** - * A mutable Acl. - * - *

- * A mutable ACL must ensure that appropriate security checks are performed - * before allowing access to its methods. - *

- * - * @author Ben Alex - * @version $Id$ +/** + * A mutable Acl. + * + *

+ * A mutable ACL must ensure that appropriate security checks are performed + * before allowing access to its methods. + *

+ * + * @author Ben Alex + * @version $Id$ */ public interface MutableAcl extends Acl { //~ Methods ======================================================================================================== - public void deleteAce(Serializable aceId) throws NotFoundException; + void deleteAce(Serializable aceId) throws NotFoundException; /** * Retrieves all of the non-deleted {@link AccessControlEntry} instances currently stored by the @@ -44,16 +44,16 @@ public interface MutableAcl extends Acl { * * @return DOCUMENT ME! */ - public AccessControlEntry[] getEntries(); + AccessControlEntry[] getEntries(); /** * Obtains an identifier that represents this MutableAcl. * * @return the identifier, or null if unsaved */ - public Serializable getId(); + Serializable getId(); - public void insertAce(Serializable afterAceId, Permission permission, Sid sid, boolean granting) + void insertAce(Serializable afterAceId, Permission permission, Sid sid, boolean granting) throws NotFoundException; /** @@ -61,15 +61,15 @@ public interface MutableAcl extends Acl { * * @param entriesInheriting the new value */ - public void setEntriesInheriting(boolean entriesInheriting); + void setEntriesInheriting(boolean entriesInheriting); /** * Changes the parent of this ACL. * * @param newParent the new parent */ - public void setParent(MutableAcl newParent); + void setParent(MutableAcl newParent); - public void updateAce(Serializable aceId, Permission permission) + void updateAce(Serializable aceId, Permission permission) throws NotFoundException; } diff --git a/core/src/main/java/org/acegisecurity/acls/MutableAclService.java b/core/src/main/java/org/acegisecurity/acls/MutableAclService.java index 9b866e052b..b741aa8f5a 100644 --- a/core/src/main/java/org/acegisecurity/acls/MutableAclService.java +++ b/core/src/main/java/org/acegisecurity/acls/MutableAclService.java @@ -17,11 +17,11 @@ package org.acegisecurity.acls; import org.acegisecurity.acls.objectidentity.ObjectIdentity; -/** - * Provides support for creating and storing Acl instances. - * - * @author Ben Alex - * @version $Id$ +/** + * Provides support for creating and storing Acl instances. + * + * @author Ben Alex + * @version $Id$ */ public interface MutableAclService extends AclService { //~ Methods ======================================================================================================== @@ -36,7 +36,7 @@ public interface MutableAclService extends AclService { * * @throws AlreadyExistsException if the passed object identity already has a record */ - public MutableAcl createAcl(ObjectIdentity objectIdentity) + MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException; /** @@ -47,7 +47,7 @@ public interface MutableAclService extends AclService { * * @throws ChildrenExistException if the deleteChildren argument was false but children exist */ - public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) + void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException; /** @@ -61,5 +61,5 @@ public interface MutableAclService extends AclService { * #createAcl(ObjectIdentity)} to create the object, rather than creating it with the new * keyword?) */ - public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException; + MutableAcl updateAcl(MutableAcl acl) throws NotFoundException; } diff --git a/core/src/main/java/org/acegisecurity/acls/OwnershipAcl.java b/core/src/main/java/org/acegisecurity/acls/OwnershipAcl.java index d8c44456a0..1a2bc32702 100644 --- a/core/src/main/java/org/acegisecurity/acls/OwnershipAcl.java +++ b/core/src/main/java/org/acegisecurity/acls/OwnershipAcl.java @@ -17,19 +17,19 @@ package org.acegisecurity.acls; import org.acegisecurity.acls.sid.Sid; -/** - * A mutable ACL that provides ownership capabilities. - * - *

- * Generally the owner of an ACL is able to call any ACL mutator method, as - * well as assign a new owner. - *

- * - * @author Ben Alex - * @version $Id$ +/** + * A mutable ACL that provides ownership capabilities. + * + *

+ * Generally the owner of an ACL is able to call any ACL mutator method, as + * well as assign a new owner. + *

+ * + * @author Ben Alex + * @version $Id$ */ public interface OwnershipAcl extends MutableAcl { //~ Methods ======================================================================================================== - public void setOwner(Sid newOwner); + void setOwner(Sid newOwner); } diff --git a/core/src/main/java/org/acegisecurity/acls/Permission.java b/core/src/main/java/org/acegisecurity/acls/Permission.java index 2104090c13..3e041525c7 100644 --- a/core/src/main/java/org/acegisecurity/acls/Permission.java +++ b/core/src/main/java/org/acegisecurity/acls/Permission.java @@ -14,21 +14,18 @@ */ package org.acegisecurity.acls; -import org.acegisecurity.acls.sid.Sid; - - -/** - * Represents a permission granted to a {@link Sid} for a given domain object. - * - * @author Ben Alex - * @version $Id$ +/** + * Represents a permission granted to a {@link org.acegisecurity.acls.sid.Sid Sid} for a given domain object. + * + * @author Ben Alex + * @version $Id$ */ public interface Permission { //~ Static fields/initializers ===================================================================================== - public static final char RESERVED_ON = '~'; - public static final char RESERVED_OFF = '.'; - public static final String THIRTY_TWO_RESERVED_OFF = "................................"; + char RESERVED_ON = '~'; + char RESERVED_OFF = '.'; + String THIRTY_TWO_RESERVED_OFF = "................................"; //~ Methods ======================================================================================================== @@ -37,20 +34,22 @@ public interface Permission { * * @return the bits that represent the permission */ - public int getMask(); + int getMask(); /** - * Returns a 32-character long bit pattern String representing this permission.

Implementations - * are free to format the pattern as they see fit, although under no circumstances may {@link #RESERVED_OFF} or - * {@link #RESERVED_ON} be used within the pattern. An exemption is in the case of {@link #RESERVED_OFF} which is - * used to denote a bit that is off (clear). Implementations may also elect to use {@link #RESERVED_ON} internally - * for computation purposes, although this method may not return any String containing {@link - * #RESERVED_ON}.

+ * Returns a 32-character long bit pattern String representing this permission. + *

+ * Implementations are free to format the pattern as they see fit, although under no circumstances may + * {@link #RESERVED_OFF} or {@link #RESERVED_ON} be used within the pattern. An exemption is in the case of + * {@link #RESERVED_OFF} which is used to denote a bit that is off (clear). + * Implementations may also elect to use {@link #RESERVED_ON} internally for computation purposes, + * although this method may not return any String containing {@link #RESERVED_ON}. + *

*

The returned String must be 32 characters in length.

*

This method is only used for user interface and logging purposes. It is not used in any permission * calculations. Therefore, duplication of characters within the output is permitted.

* * @return a 32-character bit pattern */ - public String getPattern(); + String getPattern(); } diff --git a/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategy.java b/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategy.java index 7530340600..6c43d062e7 100644 --- a/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategy.java +++ b/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategy.java @@ -21,18 +21,18 @@ import org.acegisecurity.acls.Acl; /** * Strategy used by {@link AclImpl} to determine whether a principal is permitted to call * adminstrative methods on the AclImpl. - * + * * @author Ben Alex * @version $Id$ */ public interface AclAuthorizationStrategy { //~ Static fields/initializers ===================================================================================== - public static final int CHANGE_OWNERSHIP = 0; - public static final int CHANGE_AUDITING = 1; - public static final int CHANGE_GENERAL = 2; + int CHANGE_OWNERSHIP = 0; + int CHANGE_AUDITING = 1; + int CHANGE_GENERAL = 2; //~ Methods ======================================================================================================== - public void securityCheck(Acl acl, int changeType); + void securityCheck(Acl acl, int changeType); } diff --git a/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategyImpl.java b/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategyImpl.java index da35c839a0..8d688546d1 100644 --- a/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategyImpl.java +++ b/core/src/main/java/org/acegisecurity/acls/domain/AclAuthorizationStrategyImpl.java @@ -53,7 +53,7 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy { /** * Constructor. The only mandatory parameter relates to the system-wide {@link GrantedAuthority} instances that * can be held to always permit ACL changes. - * + * * @param auths an array of GrantedAuthoritys that have * special permissions (index 0 is the authority needed to change * ownership, index 1 is the authority needed to modify auditing details, @@ -81,7 +81,8 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy { // Check if authorized by virtue of ACL ownership Sid currentUser = new PrincipalSid(authentication); - if (currentUser.equals(acl.getOwner()) && ((changeType == CHANGE_GENERAL) || (changeType == CHANGE_OWNERSHIP))) { + if (currentUser.equals(acl.getOwner()) + && ((changeType == CHANGE_GENERAL) || (changeType == CHANGE_OWNERSHIP))) { return; } diff --git a/core/src/main/java/org/acegisecurity/acls/domain/AuditLogger.java b/core/src/main/java/org/acegisecurity/acls/domain/AuditLogger.java index 9bf11e9276..8c725d463c 100644 --- a/core/src/main/java/org/acegisecurity/acls/domain/AuditLogger.java +++ b/core/src/main/java/org/acegisecurity/acls/domain/AuditLogger.java @@ -17,15 +17,15 @@ package org.acegisecurity.acls.domain; import org.acegisecurity.acls.AccessControlEntry; -/** - * Used by AclImpl to log audit events. - * - * @author Ben Alex - * @version $Id$ - * +/** + * Used by AclImpl to log audit events. + * + * @author Ben Alex + * @version $Id$ + * */ public interface AuditLogger { //~ Methods ======================================================================================================== - public void logIfNeeded(boolean granted, AccessControlEntry ace); + void logIfNeeded(boolean granted, AccessControlEntry ace); } diff --git a/core/src/main/java/org/acegisecurity/acls/domain/BasePermission.java b/core/src/main/java/org/acegisecurity/acls/domain/BasePermission.java index 58e4d3ba9a..19d23cedad 100644 --- a/core/src/main/java/org/acegisecurity/acls/domain/BasePermission.java +++ b/core/src/main/java/org/acegisecurity/acls/domain/BasePermission.java @@ -33,7 +33,7 @@ import java.util.Vector; * @author Ben Alex * @version $Id$ */ -public class BasePermission implements Permission { +public final class BasePermission implements Permission { //~ Static fields/initializers ===================================================================================== public static final Permission READ = new BasePermission(1 << 0, 'R'); // 1 diff --git a/core/src/main/java/org/acegisecurity/acls/domain/ConsoleAuditLogger.java b/core/src/main/java/org/acegisecurity/acls/domain/ConsoleAuditLogger.java index da867b0bdf..f10f72d8e0 100644 --- a/core/src/main/java/org/acegisecurity/acls/domain/ConsoleAuditLogger.java +++ b/core/src/main/java/org/acegisecurity/acls/domain/ConsoleAuditLogger.java @@ -31,9 +31,9 @@ public class ConsoleAuditLogger implements AuditLogger { public void logIfNeeded(boolean granted, AccessControlEntry ace) { Assert.notNull(ace, "AccessControlEntry required"); - + if (ace instanceof AuditableAccessControlEntry) { - AuditableAccessControlEntry auditableAce = (AuditableAccessControlEntry) ace; + AuditableAccessControlEntry auditableAce = (AuditableAccessControlEntry) ace; if (granted && auditableAce.isAuditSuccess()) { System.out.println("GRANTED due to ACE: " + ace); diff --git a/core/src/main/java/org/acegisecurity/acls/jdbc/AclCache.java b/core/src/main/java/org/acegisecurity/acls/jdbc/AclCache.java index 25743d5c33..106c0f7325 100644 --- a/core/src/main/java/org/acegisecurity/acls/jdbc/AclCache.java +++ b/core/src/main/java/org/acegisecurity/acls/jdbc/AclCache.java @@ -20,23 +20,23 @@ import org.acegisecurity.acls.objectidentity.ObjectIdentity; import java.io.Serializable; -/** - * A caching layer for {@link JdbcAclService}. - * - * @author Ben Alex - * @version $Id$ - * +/** + * A caching layer for {@link JdbcAclService}. + * + * @author Ben Alex + * @version $Id$ + * */ public interface AclCache { //~ Methods ======================================================================================================== - public void evictFromCache(Serializable pk); + void evictFromCache(Serializable pk); - public void evictFromCache(ObjectIdentity objectIdentity); + void evictFromCache(ObjectIdentity objectIdentity); - public MutableAcl getFromCache(ObjectIdentity objectIdentity); + MutableAcl getFromCache(ObjectIdentity objectIdentity); - public MutableAcl getFromCache(Serializable pk); + MutableAcl getFromCache(Serializable pk); - public void putInCache(MutableAcl acl); + void putInCache(MutableAcl acl); } diff --git a/core/src/main/java/org/acegisecurity/acls/jdbc/BasicLookupStrategy.java b/core/src/main/java/org/acegisecurity/acls/jdbc/BasicLookupStrategy.java index e62263b0a2..ece12047a5 100644 --- a/core/src/main/java/org/acegisecurity/acls/jdbc/BasicLookupStrategy.java +++ b/core/src/main/java/org/acegisecurity/acls/jdbc/BasicLookupStrategy.java @@ -79,12 +79,12 @@ public final class BasicLookupStrategy implements LookupStrategy { //~ Constructors =================================================================================================== -/** - * Constructor accepting mandatory arguments - * - * @param dataSource to access the database - * @param aclCache the cache where fully-loaded elements can be stored - * @param aclAuthorizationStrategy authorization strategy (required) +/** + * Constructor accepting mandatory arguments + * + * @param dataSource to access the database + * @param aclCache the cache where fully-loaded elements can be stored + * @param aclAuthorizationStrategy authorization strategy (required) */ public BasicLookupStrategy(DataSource dataSource, AclCache aclCache, AclAuthorizationStrategy aclAuthorizationStrategy, AuditLogger auditLogger) { @@ -106,7 +106,8 @@ public final class BasicLookupStrategy implements LookupStrategy { 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_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, ACL_SID ACLI_SID, ACL_CLASS " @@ -387,7 +388,8 @@ public final class BasicLookupStrategy implements LookupStrategy { continue; // now in results, so move to next element } else { throw new IllegalStateException( - "Error: SID-filtered element detected when implementation does not perform SID filtering - have you added something to the cache manually?"); + "Error: SID-filtered element detected when implementation does not perform SID filtering " + + "- have you added something to the cache manually?"); } } diff --git a/core/src/main/java/org/acegisecurity/acls/jdbc/JdbcMutableAclService.java b/core/src/main/java/org/acegisecurity/acls/jdbc/JdbcMutableAclService.java index d4f036d7d5..ec63c871b9 100644 --- a/core/src/main/java/org/acegisecurity/acls/jdbc/JdbcMutableAclService.java +++ b/core/src/main/java/org/acegisecurity/acls/jdbc/JdbcMutableAclService.java @@ -128,7 +128,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS } public void setValues(PreparedStatement stmt, int i) - throws SQLException { + throws SQLException { AccessControlEntry entry_ = (AccessControlEntry) Array.get(acl.getEntries(), i); Assert.isTrue(entry_ instanceof AccessControlEntryImpl, "Unknown ACE class"); @@ -176,7 +176,8 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS if (allowCreate) { classId = null; jdbcTemplate.update(insertClass, new Object[] {clazz.getName()}); - Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); + Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), + "Transaction must be running"); classId = new Long(jdbcTemplate.queryForLong(identityQuery)); } } else { @@ -220,7 +221,8 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS if (allowCreate) { sidId = null; jdbcTemplate.update(insertSid, new Object[] {new Boolean(principal), sidName}); - Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); + Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), + "Transaction must be running"); sidId = new Long(jdbcTemplate.queryForLong(identityQuery)); } } else { @@ -263,7 +265,8 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS * @param oid the rows in acl_entry to delete */ protected void deleteEntries(ObjectIdentity oid) { - jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey, new Object[] {retrieveObjectIdentityPrimaryKey(oid)}); + jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey, + new Object[] {retrieveObjectIdentityPrimaryKey(oid)}); } /** diff --git a/core/src/main/java/org/acegisecurity/acls/jdbc/LookupStrategy.java b/core/src/main/java/org/acegisecurity/acls/jdbc/LookupStrategy.java index 6bb0cef91c..f2f95a28b1 100644 --- a/core/src/main/java/org/acegisecurity/acls/jdbc/LookupStrategy.java +++ b/core/src/main/java/org/acegisecurity/acls/jdbc/LookupStrategy.java @@ -20,11 +20,11 @@ import org.acegisecurity.acls.sid.Sid; import java.util.Map; -/** - * Performs optimised lookups for {@link JdbcAclService}. - * - * @author Ben Alex - * @version $Id$ +/** + * Performs optimised lookups for {@link JdbcAclService}. + * + * @author Ben Alex + * @version $Id$ */ public interface LookupStrategy { //~ Methods ======================================================================================================== @@ -39,5 +39,5 @@ public interface LookupStrategy { * @return the Map pursuant to the interface contract for {@link * org.acegisecurity.acls.AclService#readAclsById(ObjectIdentity[], Sid[])} */ - public Map readAclsById(ObjectIdentity[] objects, Sid[] sids); + Map readAclsById(ObjectIdentity[] objects, Sid[] sids); } diff --git a/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentity.java b/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentity.java index c8b347693f..169ebf3bbe 100644 --- a/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentity.java +++ b/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentity.java @@ -17,20 +17,20 @@ package org.acegisecurity.acls.objectidentity; import java.io.Serializable; -/** - * Interface representing the identity of an individual domain object instance. - * - *

- * As implementations are used as the key for caching and lookup, it is - * essential that implementations provide methods so that object-equality - * rather than reference-equality can be relied upon by caches. In other - * words, a cache can consider two ObjectIdentitys equal if - * identity1.equals(identity2), rather than reference-equality of - * identity1==identity2. - *

- * - * @author Ben Alex - * @version $Id$ +/** + * Interface representing the identity of an individual domain object instance. + * + *

+ * As implementations are used as the key for caching and lookup, it is + * essential that implementations provide methods so that object-equality + * rather than reference-equality can be relied upon by caches. In other + * words, a cache can consider two ObjectIdentitys equal if + * identity1.equals(identity2), rather than reference-equality of + * identity1==identity2. + *

+ * + * @author Ben Alex + * @version $Id$ */ public interface ObjectIdentity extends Serializable { //~ Methods ======================================================================================================== @@ -42,7 +42,7 @@ public interface ObjectIdentity extends Serializable { * * @return true if the objects are equal, false otherwise */ - public boolean equals(Object obj); + boolean equals(Object obj); /** * Obtains the actual identifier. This identifier must not be reused to represent other domain objects with @@ -52,19 +52,19 @@ public interface ObjectIdentity extends Serializable { * * @return the identifier (unique within this javaType */ - public Serializable getIdentifier(); + Serializable getIdentifier(); /** * Obtains the Java type represented by the domain object. * * @return the Java type of the domain object */ - public Class getJavaType(); + Class getJavaType(); /** * Refer to the java.lang.Object documentation for the interface contract. * * @return a hash code representation of this object */ - public int hashCode(); + int hashCode(); } diff --git a/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityImpl.java b/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityImpl.java index 5098aab5a5..06a7282552 100644 --- a/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityImpl.java +++ b/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityImpl.java @@ -14,8 +14,6 @@ */ package org.acegisecurity.acls.objectidentity; -import org.acegisecurity.acl.basic.AclObjectIdentity; - import org.acegisecurity.acls.IdentityUnavailableException; import org.springframework.util.Assert; @@ -27,8 +25,11 @@ import java.lang.reflect.Method; /** - * Simple implementation of {@link AclObjectIdentity}.

Uses Strings to store the identity of the - * domain object instance. Also offers a constructor that uses reflection to build the identity information.

+ * Simple implementation of {@link org.acegisecurity.acl.basic.AclObjectIdentity AclObjectIdentity}. + *

+ * Uses Strings to store the identity of the domain object instance. Also offers a constructor that uses + * reflection to build the identity information. + *

*/ public class ObjectIdentityImpl implements ObjectIdentity { //~ Instance fields ================================================================================================ @@ -58,16 +59,16 @@ public class ObjectIdentityImpl implements ObjectIdentity { this.identifier = identifier; } -/** - * Creates the ObjectIdentityImpl based on the passed - * object instance. The passed object must provide a getId() - * method, otherwise an exception will be thrown. The object passed will - * be considered the {@link #javaType}, so if more control is required, - * an alternate constructor should be used instead. - * - * @param object the domain object instance to create an identity for - * - * @throws IdentityUnavailableException if identity could not be extracted +/** + * Creates the ObjectIdentityImpl based on the passed + * object instance. The passed object must provide a getId() + * method, otherwise an exception will be thrown. The object passed will + * be considered the {@link #javaType}, so if more control is required, + * an alternate constructor should be used instead. + * + * @param object the domain object instance to create an identity for + * + * @throws IdentityUnavailableException if identity could not be extracted */ public ObjectIdentityImpl(Object object) throws IdentityUnavailableException { Assert.notNull(object, "object cannot be null"); diff --git a/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityRetrievalStrategy.java b/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityRetrievalStrategy.java index 7687ab21b1..bf1c4f78ba 100644 --- a/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityRetrievalStrategy.java +++ b/core/src/main/java/org/acegisecurity/acls/objectidentity/ObjectIdentityRetrievalStrategy.java @@ -18,7 +18,7 @@ package org.acegisecurity.acls.objectidentity; /** * Strategy interface that provides the ability to determine which {@link ObjectIdentity} * will be returned for a particular domain object - * + * * @author Ben Alex * @version $Id$ * @@ -26,5 +26,5 @@ package org.acegisecurity.acls.objectidentity; public interface ObjectIdentityRetrievalStrategy { //~ Methods ======================================================================================================== - public ObjectIdentity getObjectIdentity(Object domainObject); + ObjectIdentity getObjectIdentity(Object domainObject); } diff --git a/core/src/main/java/org/acegisecurity/acls/sid/Sid.java b/core/src/main/java/org/acegisecurity/acls/sid/Sid.java index 96cbdbe9fe..477fd3a0fe 100644 --- a/core/src/main/java/org/acegisecurity/acls/sid/Sid.java +++ b/core/src/main/java/org/acegisecurity/acls/sid/Sid.java @@ -14,20 +14,20 @@ */ package org.acegisecurity.acls.sid; -/** - * A security identity recognised by the ACL system. - * - *

- * This interface provides indirection between actual security objects (eg - * principals, roles, groups etc) and what is stored inside an - * Acl. This is because an Acl will not store an - * entire security object, but only an abstraction of it. This interface - * therefore provides a simple way to compare these abstracted security - * identities with other security identities and actual security objects. - *

- * - * @author Ben Alex - * @version $Id$ +/** + * A security identity recognised by the ACL system. + * + *

+ * This interface provides indirection between actual security objects (eg + * principals, roles, groups etc) and what is stored inside an + * Acl. This is because an Acl will not store an + * entire security object, but only an abstraction of it. This interface + * therefore provides a simple way to compare these abstracted security + * identities with other security identities and actual security objects. + *

+ * + * @author Ben Alex + * @version $Id$ */ public interface Sid { //~ Methods ======================================================================================================== @@ -39,12 +39,12 @@ public interface Sid { * * @return true if the objects are equal, false otherwise */ - public boolean equals(Object obj); + boolean equals(Object obj); /** * Refer to the java.lang.Object documentation for the interface contract. * * @return a hash code representation of this object */ - public int hashCode(); + int hashCode(); } diff --git a/core/src/main/java/org/acegisecurity/acls/sid/SidRetrievalStrategy.java b/core/src/main/java/org/acegisecurity/acls/sid/SidRetrievalStrategy.java index 209bae7209..c46b62212b 100644 --- a/core/src/main/java/org/acegisecurity/acls/sid/SidRetrievalStrategy.java +++ b/core/src/main/java/org/acegisecurity/acls/sid/SidRetrievalStrategy.java @@ -21,12 +21,12 @@ import org.acegisecurity.Authentication; /** * Strategy interface that provides an ability to determine the {@link Sid} instances applicable * for an {@link Authentication}. - * + * * @author Ben Alex * @version $Id$ */ public interface SidRetrievalStrategy { //~ Methods ======================================================================================================== - public Sid[] getSids(Authentication authentication); + Sid[] getSids(Authentication authentication); } diff --git a/core/src/main/java/org/acegisecurity/adapters/AuthByAdapter.java b/core/src/main/java/org/acegisecurity/adapters/AuthByAdapter.java index b1f99feb11..50af9fe47d 100644 --- a/core/src/main/java/org/acegisecurity/adapters/AuthByAdapter.java +++ b/core/src/main/java/org/acegisecurity/adapters/AuthByAdapter.java @@ -21,7 +21,7 @@ import org.acegisecurity.Authentication; /** * Indicates a specialized, immutable, server-side only {@link Authentication} * class. - * + * *

* Automatically considered valid by the {@link AuthByAdapterProvider}, * provided the hash code presented by the implementation objects matches that @@ -41,5 +41,5 @@ public interface AuthByAdapter extends Authentication { * * @return the hash code of the key used when the object was created. */ - public int getKeyHash(); + int getKeyHash(); } diff --git a/core/src/main/java/org/acegisecurity/adapters/PrincipalAcegiUserToken.java b/core/src/main/java/org/acegisecurity/adapters/PrincipalAcegiUserToken.java index 94d1d83e10..373f6efd4d 100644 --- a/core/src/main/java/org/acegisecurity/adapters/PrincipalAcegiUserToken.java +++ b/core/src/main/java/org/acegisecurity/adapters/PrincipalAcegiUserToken.java @@ -29,7 +29,7 @@ import java.security.Principal; public class PrincipalAcegiUserToken extends AbstractAdapterAuthenticationToken implements Principal { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Object principal; private String password; private String username; diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationCollectionFilteringProvider.java b/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationCollectionFilteringProvider.java index 22312fe534..c0e3955443 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationCollectionFilteringProvider.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationCollectionFilteringProvider.java @@ -20,7 +20,6 @@ import org.acegisecurity.AuthorizationServiceException; import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttributeDefinition; -import org.acegisecurity.acls.Acl; import org.acegisecurity.acls.AclService; import org.acegisecurity.acls.Permission; @@ -39,7 +38,9 @@ import java.util.Iterator; * each Collection domain object instance element for the current Authentication object.

*

This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} matches the {@link * #processConfigAttribute}. The provider will then lookup the ACLs from the AclService and ensure the - * principal is {@link Acl#isGranted(org.acegisecurity.acls.Permission[], org.acegisecurity.acls.sid.Sid[], boolean)} + * principal is + * {@link org.acegisecurity.acls.Acl#isGranted(org.acegisecurity.acls.Permission[], + * org.acegisecurity.acls.sid.Sid[], boolean) Acl.isGranted(Permission[], Sid[], boolean)} * when presenting the {@link #requirePermission} array to that method.

*

If the principal does not have permission, that element will not be included in the returned * Collection.

@@ -94,9 +95,8 @@ public class AclEntryAfterInvocationCollectionFilteringProvider extends Abstract Object[] array = (Object[]) returnedObject; filterer = new ArrayFilterer(array); } else { - throw new AuthorizationServiceException( - "A Collection or an array (or null) was required as the returnedObject, but the returnedObject was: " - + returnedObject); + throw new AuthorizationServiceException("A Collection or an array (or null) was required as the " + + "returnedObject, but the returnedObject was: " + returnedObject); } // Locate unauthorised Collection elements diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationProvider.java b/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationProvider.java index 4dd9b440b5..a3a2a18acd 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationProvider.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/AclEntryAfterInvocationProvider.java @@ -20,7 +20,6 @@ import org.acegisecurity.Authentication; import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttributeDefinition; -import org.acegisecurity.acls.Acl; import org.acegisecurity.acls.AclService; import org.acegisecurity.acls.Permission; @@ -37,19 +36,20 @@ import java.util.Iterator; /** *

Given a domain object instance returned from a secure object invocation, ensures the principal has * appropriate permission as defined by the {@link AclService}.

- *

The AclService is used to retrieve the access control list (ACL) permissions associated with a + *

The AclService is used to retrieve the access control list (ACL) permissions associated with a * domain object instance for the current Authentication object.

- *

This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} matches the {@link + *

This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} matches the {@link * #processConfigAttribute}. The provider will then lookup the ACLs from the AclService and ensure the - * principal is {@link Acl#isGranted(org.acegisecurity.acls.Permission[], org.acegisecurity.acls.sid.Sid[], boolean)} + * principal is {@link org.acegisecurity.acls.Acl#isGranted(org.acegisecurity.acls.Permission[], + org.acegisecurity.acls.sid.Sid[], boolean) Acl.isGranted(Permission[], Sid[], boolean)} * when presenting the {@link #requirePermission} array to that method.

- *

Often users will setup an AclEntryAfterInvocationProvider with a {@link + *

Often users will setup an AclEntryAfterInvocationProvider with a {@link * #processConfigAttribute} of AFTER_ACL_READ and a {@link #requirePermission} of * BasePermission.READ. These are also the defaults.

- *

If the principal does not have sufficient permissions, an AccessDeniedException will be thrown.

- *

If the provided returnObject is null, permission will always be granted and + *

If the principal does not have sufficient permissions, an AccessDeniedException will be thrown.

+ *

If the provided returnObject is null, permission will always be granted and * null will be returned.

- *

All comparisons and prefixes are case sensitive.

+ *

All comparisons and prefixes are case sensitive.

*/ public class AclEntryAfterInvocationProvider extends AbstractAclProvider implements MessageSourceAware { //~ Static fields/initializers ===================================================================================== @@ -113,7 +113,7 @@ public class AclEntryAfterInvocationProvider extends AbstractAclProvider impleme return returnedObject; } - public void setMessageSource(MessageSource messages) { - this.messages = new MessageSourceAccessor(messages); + public void setMessageSource(MessageSource messageSource) { + this.messages = new MessageSourceAccessor(messageSource); } } diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/AfterInvocationProvider.java b/core/src/main/java/org/acegisecurity/afterinvocation/AfterInvocationProvider.java index 48bcefb009..0d9ddf858c 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/AfterInvocationProvider.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/AfterInvocationProvider.java @@ -31,7 +31,7 @@ import org.acegisecurity.ConfigAttributeDefinition; public interface AfterInvocationProvider { //~ Methods ======================================================================================================== - public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config, + Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config, Object returnedObject) throws AccessDeniedException; /** @@ -46,7 +46,7 @@ public interface AfterInvocationProvider { * * @return true if this AfterInvocationProvider can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); /** * Indicates whether the AfterInvocationProvider is able to provide "after invocation" @@ -56,5 +56,5 @@ public interface AfterInvocationProvider { * * @return true if the implementation can process the indicated class */ - public boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/ArrayFilterer.java b/core/src/main/java/org/acegisecurity/afterinvocation/ArrayFilterer.java index 4b8def73ca..c0733114dd 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/ArrayFilterer.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/ArrayFilterer.java @@ -36,7 +36,8 @@ import java.util.Set; class ArrayFilterer implements Filterer { //~ Static fields/initializers ===================================================================================== - protected static final Log logger = LogFactory.getLog(BasicAclEntryAfterInvocationCollectionFilteringProvider.class); + protected static final Log logger = + LogFactory.getLog(BasicAclEntryAfterInvocationCollectionFilteringProvider.class); //~ Instance fields ================================================================================================ @@ -57,7 +58,7 @@ class ArrayFilterer implements Filterer { //~ Methods ======================================================================================================== /** - * + * * @see org.acegisecurity.afterinvocation.Filterer#getFilteredObject() */ public Object getFilteredObject() { @@ -84,7 +85,7 @@ class ArrayFilterer implements Filterer { } /** - * + * * @see org.acegisecurity.afterinvocation.Filterer#iterator() */ public Iterator iterator() { @@ -92,7 +93,7 @@ class ArrayFilterer implements Filterer { } /** - * + * * @see org.acegisecurity.afterinvocation.Filterer#remove(java.lang.Object) */ public void remove(Object object) { diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java b/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java index 9d98d7a0d7..b39c67efc8 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationCollectionFilteringProvider.java @@ -116,9 +116,8 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProvider implements Object[] array = (Object[]) returnedObject; filterer = new ArrayFilterer(array); } else { - throw new AuthorizationServiceException( - "A Collection or an array (or null) was required as the returnedObject, but the returnedObject was: " - + returnedObject); + throw new AuthorizationServiceException("A Collection or an array (or null) was required as the " + + "returnedObject, but the returnedObject was: " + returnedObject); } // Locate unauthorised Collection elements @@ -207,12 +206,12 @@ public class BasicAclEntryAfterInvocationCollectionFilteringProvider implements * Allow setting permissions with String literals instead of integers as {@link * #setRequirePermission(int[])} * - * @param requirePermission permission literals + * @param requiredPermissions permission literals * * @see SimpleAclEntry#parsePermissions(String[]) for valid values */ - public void setRequirePermissionFromString(String[] requirePermission) { - setRequirePermission(SimpleAclEntry.parsePermissions(requirePermission)); + public void setRequirePermissionFromString(String[] requiredPermissions) { + setRequirePermission(SimpleAclEntry.parsePermissions(requiredPermissions)); } public boolean supports(ConfigAttribute attribute) { diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationProvider.java b/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationProvider.java index 390bd2f9a7..7866736e0a 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationProvider.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/BasicAclEntryAfterInvocationProvider.java @@ -146,7 +146,8 @@ public class BasicAclEntryAfterInvocationProvider implements AfterInvocationProv throw new AccessDeniedException(messages.getMessage( "BasicAclEntryAfterInvocationProvider.insufficientPermission", new Object[] {authentication.getName(), returnedObject}, - "Authentication {0} has ACL permissions to the domain object, but not the required ACL permission to the domain object {1}")); + "Authentication {0} has ACL permissions to the domain object, " + + "but not the required ACL permission to the domain object {1}")); } } @@ -188,12 +189,12 @@ public class BasicAclEntryAfterInvocationProvider implements AfterInvocationProv /** * Allow setting permissions with String literals instead of integers as {@link #setRequirePermission(int[])} - * - * @param requirePermission Permission literals + * + * @param requiredPermissions Permission literals * @see SimpleAclEntry#parsePermissions(String[]) for valid values */ - public void setRequirePermissionFromString(String[] requirePermission) { - setRequirePermission(SimpleAclEntry.parsePermissions(requirePermission)); + public void setRequirePermissionFromString(String[] requiredPermissions) { + setRequirePermission(SimpleAclEntry.parsePermissions(requiredPermissions)); } public boolean supports(ConfigAttribute attribute) { diff --git a/core/src/main/java/org/acegisecurity/afterinvocation/Filterer.java b/core/src/main/java/org/acegisecurity/afterinvocation/Filterer.java index fb334b4aae..bc4e1e4e29 100644 --- a/core/src/main/java/org/acegisecurity/afterinvocation/Filterer.java +++ b/core/src/main/java/org/acegisecurity/afterinvocation/Filterer.java @@ -20,7 +20,7 @@ import java.util.Iterator; /** * Filter strategy interface. - * + * * @author Ben Alex * @author Paulo Neves * @version $Id$ @@ -33,19 +33,19 @@ interface Filterer { * * @return the filtered collection or array */ - public Object getFilteredObject(); + Object getFilteredObject(); /** * Returns an iterator over the filtered collection or array. * * @return an Iterator */ - public Iterator iterator(); + Iterator iterator(); /** * Removes the the given object from the resulting list. * * @param object the object to be removed */ - public void remove(Object object); + void remove(Object object); } diff --git a/core/src/main/java/org/acegisecurity/captcha/CaptchaEntryPoint.java b/core/src/main/java/org/acegisecurity/captcha/CaptchaEntryPoint.java index fc9467ce82..83767816a1 100644 --- a/core/src/main/java/org/acegisecurity/captcha/CaptchaEntryPoint.java +++ b/core/src/main/java/org/acegisecurity/captcha/CaptchaEntryPoint.java @@ -44,11 +44,15 @@ import javax.servlet.http.HttpServletResponse; /** - * The captcha entry point : redirect to the captcha test page.

This entry point can force the use of SSL : - * see {@link #getForceHttps()}

- * This entry point allows internal OR external redirect : see {@link #setOutsideWebApp(boolean)}
- * / Original request can be added to the redirect path using a custom translation : see {@link #setIncludeOriginalRequest(boolean)}
- * Original request is translated using URLEncoding and the following translation mapping in the redirect url : + * The captcha entry point : redirect to the captcha test page. + *

+ * This entry point can force the use of SSL : see {@link #getForceHttps()} + *

+ *

+ * This entry point allows internal OR external redirect : see {@link #setOutsideWebApp(boolean)}
+ * / Original request can be added to the redirect path using a custom translation : see + * {@link #setIncludeOriginalRequest(boolean)}
+ * The original request is translated using URLEncoding and the following translation mapping in the redirect url : *

    *
  • original url => {@link #getOriginalRequestUrlParameterName()}
  • *
  • If {@link #isIncludeOriginalParameters()}
  • @@ -63,17 +67,20 @@ import javax.servlet.http.HttpServletResponse; * *
*

- * Default values :
- * forceHttps = false
- * includesOriginalRequest = true
- * includesOriginalParameters = false
- * isOutsideWebApp=false
- * originalRequestUrlParameterName =original_requestUrl
- * originalRequestParametersParameterName = original_request_parameters
- * originalRequestParametersNameValueSeparator = __
- * originalRequestParametersSeparator = ;;
- * originalRequestMethodParameterName = original_request_method
- * urlEncodingCharset = UTF-8
+ * Default values : + *
+ * forceHttps = false
+ * includesOriginalRequest = true
+ * includesOriginalParameters = false
+ * isOutsideWebApp = false
+ * originalRequestUrlParameterName = original_requestUrl
+ * originalRequestParametersParameterName = original_request_parameters
+ * originalRequestParametersNameValueSeparator = __
+ * originalRequestParametersSeparator = ;;
+ * originalRequestMethodParameterName = original_request_method
+ * urlEncodingCharset = UTF-8
+ * 
+ *

* * @author marc antoine Garrigue * @version $Id$ @@ -81,8 +88,6 @@ import javax.servlet.http.HttpServletResponse; public class CaptchaEntryPoint implements ChannelEntryPoint, InitializingBean { //~ Static fields/initializers ===================================================================================== - // ~ Static fields/initializers - // ============================================= private static final Log logger = LogFactory.getLog(CaptchaEntryPoint.class); //~ Instance fields ================================================================================================ diff --git a/core/src/main/java/org/acegisecurity/captcha/CaptchaValidationProcessingFilter.java b/core/src/main/java/org/acegisecurity/captcha/CaptchaValidationProcessingFilter.java index f9a6974bf5..c0db5f73c5 100644 --- a/core/src/main/java/org/acegisecurity/captcha/CaptchaValidationProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/captcha/CaptchaValidationProcessingFilter.java @@ -44,14 +44,10 @@ import javax.servlet.http.HttpSession; public class CaptchaValidationProcessingFilter implements InitializingBean, Filter { //~ Static fields/initializers ===================================================================================== - // ~ Static fields/initializers - // ============================================= protected static final Log logger = LogFactory.getLog(CaptchaValidationProcessingFilter.class); //~ Instance fields ================================================================================================ - // ~ Instance fields - // ======================================================== private CaptchaServiceProxy captchaService; private String captchaValidationParameter = "_captcha_parameter"; @@ -74,9 +70,9 @@ public class CaptchaValidationProcessingFilter implements InitializingBean, Filt public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - String captcha_reponse = request.getParameter(captchaValidationParameter); + String captchaResponse = request.getParameter(captchaValidationParameter); - if ((request != null) && request instanceof HttpServletRequest && (captcha_reponse != null)) { + if ((request != null) && request instanceof HttpServletRequest && (captchaResponse != null)) { logger.debug("captcha validation parameter found"); // validate the request against CaptchaServiceProxy @@ -89,7 +85,7 @@ public class CaptchaValidationProcessingFilter implements InitializingBean, Filt if (session != null) { String id = session.getId(); - valid = this.captchaService.validateReponseForId(id, captcha_reponse); + valid = this.captchaService.validateReponseForId(id, captchaResponse); logger.debug("captchaServiceProxy says : request is valid = " + valid); if (valid) { @@ -114,8 +110,6 @@ public class CaptchaValidationProcessingFilter implements InitializingBean, Filt chain.doFilter(request, response); } - // ~ Methods - // ================================================================ public CaptchaServiceProxy getCaptchaService() { return captchaService; } diff --git a/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionController.java b/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionController.java index e4ccd911b6..692a781781 100644 --- a/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionController.java +++ b/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionController.java @@ -41,7 +41,7 @@ public interface ConcurrentSessionController { * * @throws AuthenticationException if the user has exceeded their maximum allowed current sessions */ - public void checkAuthenticationAllowed(Authentication request) + void checkAuthenticationAllowed(Authentication request) throws AuthenticationException; /** @@ -51,5 +51,5 @@ public interface ConcurrentSessionController { * * @param authentication the successfully authenticated user (never null) */ - public void registerSuccessfulAuthentication(Authentication authentication); + void registerSuccessfulAuthentication(Authentication authentication); } diff --git a/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionControllerImpl.java b/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionControllerImpl.java index 632798ef84..22cf7383ab 100644 --- a/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionControllerImpl.java +++ b/core/src/main/java/org/acegisecurity/concurrent/ConcurrentSessionControllerImpl.java @@ -67,14 +67,16 @@ public class ConcurrentSessionControllerImpl implements ConcurrentSessionControl SessionRegistry registry) { if (exceptionIfMaximumExceeded || (sessions == null)) { throw new ConcurrentLoginException(messages.getMessage("ConcurrentSessionControllerImpl.exceededAllowed", - new Object[] {new Integer(allowableSessions)}, "Maximum sessions of {0} for this principal exceeded")); + new Object[] {new Integer(allowableSessions)}, + "Maximum sessions of {0} for this principal exceeded")); } // Determine least recently used session, and mark it for invalidation SessionInformation leastRecentlyUsed = null; for (int i = 0; i < sessions.length; i++) { - if ((leastRecentlyUsed == null) || sessions[i].getLastRequest().before(leastRecentlyUsed.getLastRequest())) { + if ((leastRecentlyUsed == null) + || sessions[i].getLastRequest().before(leastRecentlyUsed.getLastRequest())) { leastRecentlyUsed = sessions[i]; } } @@ -98,8 +100,8 @@ public class ConcurrentSessionControllerImpl implements ConcurrentSessionControl } int allowableSessions = getMaximumSessionsForThisUser(request); - Assert.isTrue(allowableSessions != 0, - "getMaximumSessionsForThisUser() must return either -1 to allow unlimited logins, or a positive integer to specify a maximum"); + Assert.isTrue(allowableSessions != 0, "getMaximumSessionsForThisUser() must return either -1 to allow " + + "unlimited logins, or a positive integer to specify a maximum"); if (sessionCount < allowableSessions) { // They haven't got too many login sessions running at present diff --git a/core/src/main/java/org/acegisecurity/concurrent/SessionIdentifierAware.java b/core/src/main/java/org/acegisecurity/concurrent/SessionIdentifierAware.java index a075eefa1b..482a467e96 100644 --- a/core/src/main/java/org/acegisecurity/concurrent/SessionIdentifierAware.java +++ b/core/src/main/java/org/acegisecurity/concurrent/SessionIdentifierAware.java @@ -18,7 +18,7 @@ package org.acegisecurity.concurrent; /** * Implemented by {@link org.acegisecurity.Authentication#getDetails()} * implementations that are capable of returning a session ID. - * + * *

* This interface is used by {@link * org.acegisecurity.concurrent.SessionRegistryUtils} to extract the session @@ -40,5 +40,5 @@ public interface SessionIdentifierAware { * * @return the session ID, or null if not known. */ - public String getSessionId(); + String getSessionId(); } diff --git a/core/src/main/java/org/acegisecurity/concurrent/SessionRegistry.java b/core/src/main/java/org/acegisecurity/concurrent/SessionRegistry.java index 8700a2adb6..93fd8ec1c7 100644 --- a/core/src/main/java/org/acegisecurity/concurrent/SessionRegistry.java +++ b/core/src/main/java/org/acegisecurity/concurrent/SessionRegistry.java @@ -29,7 +29,7 @@ public interface SessionRegistry { * * @return each of the unique principals, which can then be presented to {@link #getAllSessions(Object, boolean)}. */ - public Object[] getAllPrincipals(); + Object[] getAllPrincipals(); /** * Obtains all the known sessions for the specified principal. Sessions that have been destroyed are not @@ -41,7 +41,7 @@ public interface SessionRegistry { * * @return the matching sessions for this principal, or null if none were found */ - public SessionInformation[] getAllSessions(Object principal, boolean includeExpiredSessions); + SessionInformation[] getAllSessions(Object principal, boolean includeExpiredSessions); /** * Obtains the session information for the specified sessionId. Even expired sessions are @@ -51,7 +51,7 @@ public interface SessionRegistry { * * @return the session information, or null if not found */ - public SessionInformation getSessionInformation(String sessionId); + SessionInformation getSessionInformation(String sessionId); /** * Updates the given sessionId so its last request time is equal to the present date and time. @@ -59,7 +59,7 @@ public interface SessionRegistry { * * @param sessionId for which to update the date and time of the last request (should never be null) */ - public void refreshLastRequest(String sessionId); + void refreshLastRequest(String sessionId); /** * Registers a new session for the specified principal. The newly registered session will not be marked for @@ -70,7 +70,7 @@ public interface SessionRegistry { * * @throws SessionAlreadyUsedException DOCUMENT ME! */ - public void registerNewSession(String sessionId, Object principal) + void registerNewSession(String sessionId, Object principal) throws SessionAlreadyUsedException; /** @@ -79,5 +79,5 @@ public interface SessionRegistry { * * @param sessionId to delete information for (should never be null) */ - public void removeSessionInformation(String sessionId); + void removeSessionInformation(String sessionId); } diff --git a/core/src/main/java/org/acegisecurity/concurrent/SessionRegistryUtils.java b/core/src/main/java/org/acegisecurity/concurrent/SessionRegistryUtils.java index e4bb621235..a37b371cf2 100644 --- a/core/src/main/java/org/acegisecurity/concurrent/SessionRegistryUtils.java +++ b/core/src/main/java/org/acegisecurity/concurrent/SessionRegistryUtils.java @@ -28,7 +28,12 @@ import org.springframework.util.Assert; * @author Ben Alex * @version $Id$ */ -public class SessionRegistryUtils { +public final class SessionRegistryUtils { + //~ Constructors =================================================================================================== + + private SessionRegistryUtils() { + } + //~ Methods ======================================================================================================== public static Object obtainPrincipalFromAuthentication(Authentication auth) { diff --git a/core/src/main/java/org/acegisecurity/context/HttpSessionContextIntegrationFilter.java b/core/src/main/java/org/acegisecurity/context/HttpSessionContextIntegrationFilter.java index 35c2dae4b7..b946495538 100644 --- a/core/src/main/java/org/acegisecurity/context/HttpSessionContextIntegrationFilter.java +++ b/core/src/main/java/org/acegisecurity/context/HttpSessionContextIntegrationFilter.java @@ -35,16 +35,22 @@ import org.springframework.util.ReflectionUtils; /** - *

Populates the {@link SecurityContextHolder} with information obtained from the HttpSession.

- *

The HttpSession will be queried to retrieve the SecurityContext that should be + * Populates the {@link SecurityContextHolder} with information obtained from the HttpSession. + * + *

+ * The HttpSession will be queried to retrieve the SecurityContext that should be * stored against the SecurityContextHolder for the duration of the web request. At the end of the web * request, any updates made to the SecurityContextHolder will be persisted back to the - * HttpSession by this filter.

- *

If a valid SecurityContext cannot be obtained from the HttpSession for whatever + * HttpSession by this filter. + *

+ *

+ * If a valid SecurityContext cannot be obtained from the HttpSession for whatever * reason, a fresh SecurityContext will be created and used instead. The created object will be of the * instance defined by the {@link #setContext(Class)} method (which defaults to {@link - * org.acegisecurity.context.SecurityContextImpl}.

- *

No HttpSession will be created by this filter if one does not already exist. If at the end of + * org.acegisecurity.context.SecurityContextImpl}. + *

+ *

+ * No HttpSession will be created by this filter if one does not already exist. If at the end of * the web request the HttpSession does not exist, a HttpSession will only be created * if the current contents of the SecurityContextHolder are not {@link * java.lang.Object#equals(java.lang.Object)} to a new instance of {@link #setContext(Class)}. This @@ -52,19 +58,25 @@ import org.springframework.util.ReflectionUtils; * SecurityContextHolder. There is one exception to this rule, that is if the {@link * #forceEagerSessionCreation} property is true, in which case sessions will always be created * irrespective of normal session-minimisation logic (the default is false, as this is resource intensive - * and not recommended).

- *

This filter will only execute once per request, to resolve servlet container (specifically Weblogic) + * and not recommended). + *

+ *

+ * This filter will only execute once per request, to resolve servlet container (specifically Weblogic) * incompatibilities.

- *

If for whatever reason no HttpSession should ever be created (eg this filter is only + *

+ * If for whatever reason no HttpSession should ever be created (eg this filter is only * being used with Basic authentication or similar clients that will never present the same jsessionid * etc), the {@link #setAllowSessionCreation(boolean)} should be set to false. Only do this if you really * need to conserve server memory and ensure all classes using the SecurityContextHolder are designed to * have no persistence of the SecurityContext between web requests. Please note that if {@link * #forceEagerSessionCreation} is true, the allowSessionCreation must also be - * true (setting it to false will cause a startup time error).

- *

This filter MUST be executed BEFORE any authentication processing mechanisms. Authentication processing + * true (setting it to false will cause a startup time error). + *

+ *

+ * This filter MUST be executed BEFORE any authentication processing mechanisms. Authentication processing * mechanisms (eg BASIC, CAS processing filters etc) expect the SecurityContextHolder to contain a valid - * SecurityContext by the time they execute.

+ * SecurityContext by the time they execute. + *

* * @author Ben Alex * @author Patrick Burleson @@ -101,28 +113,28 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi * are conscious of the session creation overhead. */ private boolean forceEagerSessionCreation = false; - + /** * Indicates whether the SecurityContext will be cloned from the HttpSession. The * default is to simply reference (ie the default is false). The default may cause issues if * concurrent threads need to have a different security identity from other threads being concurrently processed * that share the same HttpSession. In most normal environments this does not represent an issue, * as changes to the security identity in one thread is allowed to affect the security identitiy in other - * threads associated with the same HttpSession. For unusual cases where this is not permitted, + * threads associated with the same HttpSession. For unusual cases where this is not permitted, * change this value to true and ensure the {@link #context} is set to a SecurityContext * that implements {@link Cloneable} and overrides the clone() method. */ private boolean cloneFromHttpSession = false; public boolean isCloneFromHttpSession() { - return cloneFromHttpSession; - } + return cloneFromHttpSession; + } - public void setCloneFromHttpSession(boolean cloneFromHttpSession) { - this.cloneFromHttpSession = cloneFromHttpSession; - } + public void setCloneFromHttpSession(boolean cloneFromHttpSession) { + this.cloneFromHttpSession = cloneFromHttpSession; + } - public HttpSessionContextIntegrationFilter() throws ServletException { + public HttpSessionContextIntegrationFilter() throws ServletException { this.contextObject = generateNewContext(); } @@ -131,7 +143,8 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi public void afterPropertiesSet() throws Exception { if ((this.context == null) || (!SecurityContext.class.isAssignableFrom(this.context))) { throw new IllegalArgumentException( - "context must be defined and implement SecurityContext (typically use org.acegisecurity.context.SecurityContextImpl; existing class is " + "context must be defined and implement SecurityContext " + + "(typically use org.acegisecurity.context.SecurityContextImpl; existing class is " + this.context + ")"); } @@ -167,27 +180,27 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi httpSessionExistedAtStartOfRequest = true; Object contextFromSessionObject = httpSession.getAttribute(ACEGI_SECURITY_CONTEXT_KEY); - + // Clone if required (see SEC-356) if (cloneFromHttpSession) { - Assert.isInstanceOf(Cloneable.class, contextFromSessionObject, "Context must implement Clonable and provide a Object.clone() method"); - try { - Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {}); - if (!m.isAccessible()) { - m.setAccessible(true); - } - contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {}); - } catch (Exception ex) { - ReflectionUtils.handleReflectionException(ex); - } + Assert.isInstanceOf(Cloneable.class, contextFromSessionObject, + "Context must implement Clonable and provide a Object.clone() method"); + try { + Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {}); + if (!m.isAccessible()) { + m.setAccessible(true); + } + contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {}); + } catch (Exception ex) { + ReflectionUtils.handleReflectionException(ex); + } } - + if (contextFromSessionObject != null) { if (contextFromSessionObject instanceof SecurityContext) { if (logger.isDebugEnabled()) { - logger.debug( - "Obtained from ACEGI_SECURITY_CONTEXT a valid SecurityContext and set to SecurityContextHolder: '" - + contextFromSessionObject + "'"); + logger.debug("Obtained from ACEGI_SECURITY_CONTEXT a valid SecurityContext and " + + "set to SecurityContextHolder: '" + contextFromSessionObject + "'"); } SecurityContextHolder.setContext((SecurityContext) contextFromSessionObject); @@ -195,23 +208,26 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi if (logger.isWarnEnabled()) { logger.warn("ACEGI_SECURITY_CONTEXT did not contain a SecurityContext but contained: '" + contextFromSessionObject - + "'; are you improperly modifying the HttpSession directly (you should always use SecurityContextHolder) or using the HttpSession attribute reserved for this class? - new SecurityContext instance associated with SecurityContextHolder"); + + "'; are you improperly modifying the HttpSession directly " + + "(you should always use SecurityContextHolder) or using the HttpSession attribute " + + "reserved for this class? - new SecurityContext instance associated with " + + "SecurityContextHolder"); } SecurityContextHolder.setContext(generateNewContext()); } } else { if (logger.isDebugEnabled()) { - logger.debug( - "HttpSession returned null object for ACEGI_SECURITY_CONTEXT - new SecurityContext instance associated with SecurityContextHolder"); + logger.debug("HttpSession returned null object for ACEGI_SECURITY_CONTEXT - new " + + "SecurityContext instance associated with SecurityContextHolder"); } SecurityContextHolder.setContext(generateNewContext()); } } else { if (logger.isDebugEnabled()) { - logger.debug( - "No HttpSession currently exists - new SecurityContext instance associated with SecurityContextHolder"); + logger.debug("No HttpSession currently exists - new SecurityContext instance " + + "associated with SecurityContextHolder"); } SecurityContextHolder.setContext(generateNewContext()); @@ -240,8 +256,8 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi if ((httpSession == null) && httpSessionExistedAtStartOfRequest) { if (logger.isDebugEnabled()) { - logger.debug( - "HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session"); + logger.debug("HttpSession is now null, but was not null at start of request; " + + "session was invalidated, so do not create a new session"); } } @@ -249,8 +265,10 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi if ((httpSession == null) && !httpSessionExistedAtStartOfRequest) { if (!allowSessionCreation) { if (logger.isDebugEnabled()) { - logger.debug( - "The HttpSession is currently null, and the HttpSessionContextIntegrationFilter is prohibited from creating a HttpSession (because the allowSessionCreation property is false) - SecurityContext thus not stored for next request"); + logger.debug("The HttpSession is currently null, and the " + + "HttpSessionContextIntegrationFilter is prohibited from creating an HttpSession " + + "(because the allowSessionCreation property is false) - SecurityContext thus not " + + "stored for next request"); } } else if (!contextObject.equals(SecurityContextHolder.getContext())) { if (logger.isDebugEnabled()) { @@ -263,17 +281,15 @@ public class HttpSessionContextIntegrationFilter implements InitializingBean, Fi } else { if (logger.isDebugEnabled()) { logger.debug( - "HttpSession is null, but SecurityContextHolder has not changed from default: ' " - + SecurityContextHolder.getContext() - + "'; not creating HttpSession or storing SecurityContextHolder contents"); + "HttpSession is null, but SecurityContextHolder has not changed from default: ' " + + SecurityContextHolder.getContext() + + "'; not creating HttpSession or storing SecurityContextHolder contents"); } } } - // If HttpSession exists, store current SecurityContextHolder - // contents - // but only if SecurityContext has actually changed (see JIRA - // SEC-37) + // If HttpSession exists, store current SecurityContextHolder contents but only if SecurityContext has + // actually changed (see JIRA SEC-37) if ((httpSession != null) && (SecurityContextHolder.getContext().hashCode() != contextWhenChainProceeded)) { httpSession.setAttribute(ACEGI_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); diff --git a/core/src/main/java/org/acegisecurity/context/SecurityContext.java b/core/src/main/java/org/acegisecurity/context/SecurityContext.java index 1c7a114dd4..f88dcc22da 100644 --- a/core/src/main/java/org/acegisecurity/context/SecurityContext.java +++ b/core/src/main/java/org/acegisecurity/context/SecurityContext.java @@ -23,7 +23,7 @@ import java.io.Serializable; /** * Interface defining the minimum security information associated with the * current thread of execution. - * + * *

* The security context is stored in a {@link SecurityContextHolder}. *

@@ -39,7 +39,7 @@ public interface SecurityContext extends Serializable { * * @return the Authentication or null if no authentication information is available */ - public Authentication getAuthentication(); + Authentication getAuthentication(); /** * Changes the currently authenticated principal, or removes the authentication information. @@ -47,5 +47,5 @@ public interface SecurityContext extends Serializable { * @param authentication the new Authentication token, or null if no further * authentication information should be stored */ - public void setAuthentication(Authentication authentication); + void setAuthentication(Authentication authentication); } diff --git a/core/src/main/java/org/acegisecurity/context/SecurityContextHolderStrategy.java b/core/src/main/java/org/acegisecurity/context/SecurityContextHolderStrategy.java index 14d70e9ba7..747790be37 100644 --- a/core/src/main/java/org/acegisecurity/context/SecurityContextHolderStrategy.java +++ b/core/src/main/java/org/acegisecurity/context/SecurityContextHolderStrategy.java @@ -17,7 +17,7 @@ package org.acegisecurity.context; /** * A strategy for storing security context information against a thread. - * + * *

* The preferred strategy is loaded by {@link * org.acegisecurity.context.SecurityContextHolder}. @@ -32,14 +32,14 @@ public interface SecurityContextHolderStrategy { /** * Clears the current context. */ - public void clearContext(); + void clearContext(); /** * Obtains the current context. * * @return a context (never null - create a default implementation if necessary) */ - public SecurityContext getContext(); + SecurityContext getContext(); /** * Sets the current context. @@ -47,5 +47,5 @@ public interface SecurityContextHolderStrategy { * @param context to the new argument (should never be null, although implementations must check if * null has been passed and throw an IllegalArgumentException in such cases) */ - public void setContext(SecurityContext context); + void setContext(SecurityContext context); } diff --git a/core/src/main/java/org/acegisecurity/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java b/core/src/main/java/org/acegisecurity/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java index a2899c1003..428faff767 100644 --- a/core/src/main/java/org/acegisecurity/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java +++ b/core/src/main/java/org/acegisecurity/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutor.java @@ -85,9 +85,8 @@ public class AuthenticationSimpleHttpInvokerRequestExecutor extends SimpleHttpIn } } else { if (logger.isDebugEnabled()) { - logger.debug( - "Unable to set BASIC authentication header as SecurityContext did not provide valid Authentication: " - + auth); + logger.debug("Unable to set BASIC authentication header as SecurityContext did not provide " + + "valid Authentication: " + auth); } } diff --git a/core/src/main/java/org/acegisecurity/event/authorization/AuthorizationFailureEvent.java b/core/src/main/java/org/acegisecurity/event/authorization/AuthorizationFailureEvent.java index 52d588b075..dde9b34ebc 100644 --- a/core/src/main/java/org/acegisecurity/event/authorization/AuthorizationFailureEvent.java +++ b/core/src/main/java/org/acegisecurity/event/authorization/AuthorizationFailureEvent.java @@ -15,9 +15,7 @@ package org.acegisecurity.event.authorization; -import org.acegisecurity.AccessDecisionManager; import org.acegisecurity.AccessDeniedException; -import org.acegisecurity.AfterInvocationManager; import org.acegisecurity.Authentication; import org.acegisecurity.ConfigAttributeDefinition; @@ -27,7 +25,8 @@ import org.acegisecurity.ConfigAttributeDefinition; * be authorized for the request. * *

This event might be thrown as a result of either an - * {@link AccessDecisionManager} or an {@link AfterInvocationManager}. + * {@link org.acegisecurity.AccessDecisionManager AccessDecisionManager} or an + * {@link org.acegisecurity.AfterInvocationManager AfterInvocationManager}. * * @author Ben Alex * @version $Id$ @@ -41,7 +40,7 @@ public class AuthorizationFailureEvent extends AbstractAuthorizationEvent { //~ Constructors =================================================================================================== -/** + /** * Construct the event. * * @param secureObject the secure object diff --git a/core/src/main/java/org/acegisecurity/event/authorization/LoggerListener.java b/core/src/main/java/org/acegisecurity/event/authorization/LoggerListener.java index 42d7b1d668..d64db5ef1b 100644 --- a/core/src/main/java/org/acegisecurity/event/authorization/LoggerListener.java +++ b/core/src/main/java/org/acegisecurity/event/authorization/LoggerListener.java @@ -23,8 +23,11 @@ import org.springframework.context.ApplicationListener; /** - * Outputs interceptor-related application events to Commons Logging.

All failures are logged at the warning - * level, with success events logged at the information level, and public invocation events logged at the debug level.

+ * Outputs interceptor-related application events to Commons Logging. + *

+ * All failures are logged at the warning level, with success events logged at the information level, + * and public invocation events logged at the debug level. + *

* * @author Ben Alex * @version $Id$ @@ -52,8 +55,9 @@ public class LoggerListener implements ApplicationListener { if (logger.isWarnEnabled()) { logger.warn("Security authorization failed due to: " + authEvent.getAccessDeniedException() - + "; authenticated principal: " + authEvent.getAuthentication() + "; secure object: " - + authEvent.getSource() + "; configuration attributes: " + authEvent.getConfigAttributeDefinition()); + + "; authenticated principal: " + authEvent.getAuthentication() + + "; secure object: " + authEvent.getSource() + + "; configuration attributes: " + authEvent.getConfigAttributeDefinition()); } } diff --git a/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java b/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java index 58cc29bde9..1c86722e86 100644 --- a/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java +++ b/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java @@ -154,7 +154,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A token.getAttr(), returnedObject); } catch (AccessDeniedException accessDeniedException) { AuthorizationFailureEvent event = new AuthorizationFailureEvent(token.getSecureObject(), - token.getAttr(), token.getAuthentication(), accessDeniedException); + token.getAttr(), token.getAuthentication(), accessDeniedException); publishEvent(event); throw accessDeniedException; @@ -196,7 +196,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A if (iter == null) { if (logger.isWarnEnabled()) { logger.warn( - "Could not validate configuration attributes as the MethodDefinitionSource did not return a ConfigAttributeDefinition Iterator"); + "Could not validate configuration attributes as the MethodDefinitionSource did not return a " + + "ConfigAttributeDefinition Iterator"); } } else { Set set = new HashSet(); @@ -239,8 +240,9 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A ConfigAttributeDefinition attr = this.obtainObjectDefinitionSource().getAttributes(object); if ((attr == null) && rejectPublicInvocations) { - throw new IllegalArgumentException( - "No public invocations are allowed via this AbstractSecurityInterceptor. This indicates a configuration error because the AbstractSecurityInterceptor.rejectPublicInvocations property is set to 'true'"); + throw new IllegalArgumentException("No public invocations are allowed via this AbstractSecurityInterceptor. " + + "This indicates a configuration error because the " + + "AbstractSecurityInterceptor.rejectPublicInvocations property is set to 'true'"); } if (attr != null) { @@ -306,7 +308,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A logger.debug("RunAsManager did not change Authentication object"); } - return new InterceptorStatusToken(authenticated, false, attr, object); // no further work post-invocation + // no further work post-invocation + return new InterceptorStatusToken(authenticated, false, attr, object); } else { if (logger.isDebugEnabled()) { logger.debug("Switching to RunAs Authentication: " + runAs.toString()); @@ -314,7 +317,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A SecurityContextHolder.getContext().setAuthentication(runAs); - return new InterceptorStatusToken(authenticated, true, attr, object); // revert to token.Authenticated post-invocation + // revert to token.Authenticated post-invocation + return new InterceptorStatusToken(authenticated, true, attr, object); } } else { if (logger.isDebugEnabled()) { @@ -406,8 +410,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A this.alwaysReauthenticate = alwaysReauthenticate; } - public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) { - this.eventPublisher = eventPublisher; + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.eventPublisher = applicationEventPublisher; } public void setAuthenticationManager(AuthenticationManager newManager) { diff --git a/core/src/main/java/org/acegisecurity/intercept/ObjectDefinitionSource.java b/core/src/main/java/org/acegisecurity/intercept/ObjectDefinitionSource.java index 7b575ffa6d..06a66ac135 100644 --- a/core/src/main/java/org/acegisecurity/intercept/ObjectDefinitionSource.java +++ b/core/src/main/java/org/acegisecurity/intercept/ObjectDefinitionSource.java @@ -42,7 +42,7 @@ public interface ObjectDefinitionSource { * @throws IllegalArgumentException if the passed object is not of a type supported by the * ObjectDefinitionSource implementation */ - public ConfigAttributeDefinition getAttributes(Object object) + ConfigAttributeDefinition getAttributes(Object object) throws IllegalArgumentException; /** @@ -52,7 +52,7 @@ public interface ObjectDefinitionSource { * * @return an iterator over all the ConfigAttributeDefinitions or null if unsupported */ - public Iterator getConfigAttributeDefinitions(); + Iterator getConfigAttributeDefinitions(); /** * Indicates whether the ObjectDefinitionSource implementation is able to provide @@ -62,5 +62,5 @@ public interface ObjectDefinitionSource { * * @return true if the implementation can process the indicated class */ - public boolean supports(Class clazz); + boolean supports(Class clazz); } diff --git a/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionAttributes.java b/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionAttributes.java index 2d30e9906b..b492dd9f66 100644 --- a/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionAttributes.java +++ b/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionAttributes.java @@ -86,7 +86,7 @@ public class MethodDefinitionAttributes extends AbstractMethodDefinitionSource { Method m = clazz.getDeclaredMethod(method.getName(), (Class[]) method.getParameterTypes()); addMethodAttributes(definition, m); } catch (Exception e) { - // this won't happen since we are getting a method from an interface that + // this won't happen since we are getting a method from an interface that // the declaring class implements } } diff --git a/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionMap.java b/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionMap.java index 93802b0cd2..62242e3cea 100644 --- a/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionMap.java +++ b/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionMap.java @@ -207,7 +207,8 @@ public class MethodDefinitionMap extends AbstractMethodDefinitionSource { try { // Look for the method on the current interface Method interfaceMethod = clazz.getDeclaredMethod(method.getName(), (Class[]) method.getParameterTypes()); - ConfigAttributeDefinition interfaceAssigned = (ConfigAttributeDefinition) this.methodMap.get(interfaceMethod); + ConfigAttributeDefinition interfaceAssigned = + (ConfigAttributeDefinition) this.methodMap.get(interfaceMethod); merge(definition, interfaceAssigned); } catch (Exception e) { // skip this interface @@ -236,7 +237,7 @@ public class MethodDefinitionMap extends AbstractMethodDefinitionSource { /** * Easier configuration of the instance, using {@link MethodDefinitionSourceMapping}. - * + * * @param mappings {@link List} of {@link MethodDefinitionSourceMapping} objects. */ public void setMappings(List mappings) { diff --git a/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionSourceEditor.java b/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionSourceEditor.java index b698eea553..1cd867720b 100644 --- a/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionSourceEditor.java +++ b/core/src/main/java/org/acegisecurity/intercept/method/MethodDefinitionSourceEditor.java @@ -30,8 +30,8 @@ import java.util.Properties; /** - * Property editor to assist with the setup of a {@link MethodDefinitionSource}.

The class creates and populates - * a {@link MethodDefinitionMap}.

+ * Property editor to assist with the setup of a {@link MethodDefinitionSource}. + *

The class creates and populates a {@link MethodDefinitionMap}.

* * @author Ben Alex * @version $Id$ diff --git a/core/src/main/java/org/acegisecurity/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java b/core/src/main/java/org/acegisecurity/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java index 9cfdf3ab0b..482e27aaf5 100644 --- a/core/src/main/java/org/acegisecurity/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java +++ b/core/src/main/java/org/acegisecurity/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java @@ -68,11 +68,12 @@ public class MethodDefinitionSourceAdvisor extends StaticMethodMatcherPointcutAd //~ Inner Classes ================================================================================================== /** - * Represents a MethodInvocation.

Required as MethodDefinitionSource only - * supports lookup of configuration attributes for MethodInvocations.

+ * Represents a MethodInvocation. + *

Required as MethodDefinitionSource only supports lookup of configuration attributes for + * MethodInvocations.

*/ class InternalMethodInvocation implements MethodInvocation { - Method method; + private Method method; public InternalMethodInvocation(Method method) { this.method = method; diff --git a/core/src/main/java/org/acegisecurity/intercept/method/aspectj/AspectJCallback.java b/core/src/main/java/org/acegisecurity/intercept/method/aspectj/AspectJCallback.java index b1e4b0583b..d7671d582d 100644 --- a/core/src/main/java/org/acegisecurity/intercept/method/aspectj/AspectJCallback.java +++ b/core/src/main/java/org/acegisecurity/intercept/method/aspectj/AspectJCallback.java @@ -27,5 +27,5 @@ package org.acegisecurity.intercept.method.aspectj; public interface AspectJCallback { //~ Methods ======================================================================================================== - public Object proceedWithObject(); + Object proceedWithObject(); } diff --git a/core/src/main/java/org/acegisecurity/intercept/web/AbstractFilterInvocationDefinitionSource.java b/core/src/main/java/org/acegisecurity/intercept/web/AbstractFilterInvocationDefinitionSource.java index 87e662eeaf..53f3e09455 100644 --- a/core/src/main/java/org/acegisecurity/intercept/web/AbstractFilterInvocationDefinitionSource.java +++ b/core/src/main/java/org/acegisecurity/intercept/web/AbstractFilterInvocationDefinitionSource.java @@ -28,9 +28,6 @@ import org.apache.commons.logging.LogFactory; * @version $Id$ */ public abstract class AbstractFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource { - //~ Static fields/initializers ===================================================================================== - - private static final Log logger = LogFactory.getLog(AbstractFilterInvocationDefinitionSource.class); //~ Methods ======================================================================================================== @@ -47,9 +44,11 @@ public abstract class AbstractFilterInvocationDefinitionSource implements Filter /** * Performs the actual lookup of the relevant ConfigAttributeDefinition for the specified - * FilterInvocation.

Provided so subclasses need only to provide one basic method to - * properly interface with the FilterInvocationDefinitionSource.

- *

Public visiblity so that tablibs or other view helper classes can access the + * FilterInvocation. + *

Provided so subclasses need only to provide one basic method to properly interface with the + * FilterInvocationDefinitionSource. + *

+ *

Public visiblity so that tablibs or other view helper classes can access the * ConfigAttributeDefinition applying to a given URI pattern without needing to construct a mock * FilterInvocation and retrieving the attibutes via the {@link #getAttributes(Object)} method.

* @@ -60,10 +59,6 @@ public abstract class AbstractFilterInvocationDefinitionSource implements Filter public abstract ConfigAttributeDefinition lookupAttributes(String url); public boolean supports(Class clazz) { - if (FilterInvocation.class.isAssignableFrom(clazz)) { - return true; - } else { - return false; - } + return FilterInvocation.class.isAssignableFrom(clazz); } } diff --git a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionMap.java b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionMap.java index 092dcfef65..c7dee8255d 100644 --- a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionMap.java +++ b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionMap.java @@ -28,9 +28,9 @@ import org.acegisecurity.ConfigAttributeDefinition; public interface FilterInvocationDefinitionMap { //~ Methods ======================================================================================================== - public void addSecureUrl(String expression, ConfigAttributeDefinition attr); + void addSecureUrl(String expression, ConfigAttributeDefinition attr); - public boolean isConvertUrlToLowercaseBeforeComparison(); + boolean isConvertUrlToLowercaseBeforeComparison(); - public void setConvertUrlToLowercaseBeforeComparison(boolean convertUrlToLowercaseBeforeComparison); + void setConvertUrlToLowercaseBeforeComparison(boolean convertUrlToLowercaseBeforeComparison); } diff --git a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java index 7e881c2438..993145c396 100644 --- a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java +++ b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceEditor.java @@ -43,7 +43,8 @@ public class FilterInvocationDefinitionSourceEditor extends PropertyEditorSuppor //~ Static fields/initializers ===================================================================================== private static final Log logger = LogFactory.getLog(FilterInvocationDefinitionSourceEditor.class); - public static final String DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON = "CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON"; + public static final String DIRECTIVE_CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON = + "CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON"; public static final String DIRECTIVE_PATTERN_TYPE_APACHE_ANT = "PATTERN_TYPE_APACHE_ANT"; //~ Methods ======================================================================================================== @@ -79,7 +80,7 @@ public class FilterInvocationDefinitionSourceEditor extends PropertyEditorSuppor BufferedReader br = new BufferedReader(new StringReader(s)); int counter = 0; String line; - + List mappings = new ArrayList(); while (true) { diff --git a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceMapping.java b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceMapping.java index 7cd8c817d4..16840959a7 100644 --- a/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceMapping.java +++ b/core/src/main/java/org/acegisecurity/intercept/web/FilterInvocationDefinitionSourceMapping.java @@ -24,7 +24,7 @@ import org.acegisecurity.ConfigAttribute; * Configuration entry for {@link FilterInvocationDefinitionSource}, that holds * the url to be protected and the {@link ConfigAttribute}s as {@link String} * that apply to that url. - * + * * @author Carlos Sanchez * @version $Id$ * @since 1.1 @@ -37,7 +37,7 @@ public class FilterInvocationDefinitionSourceMapping { /** * Url to be secured. - * + * * @param url */ public void setUrl(String url) { @@ -46,7 +46,7 @@ public class FilterInvocationDefinitionSourceMapping { /** * Url to be secured. - * + * * @return the url */ public String getUrl() { @@ -55,15 +55,14 @@ public class FilterInvocationDefinitionSourceMapping { /** * - * @param roles - * {@link List}<{@link String}> + * @param roles {@link List}<{@link String}> */ public void setConfigAttributes(List roles) { this.configAttributes = roles; } /** - * + * * @return {@link List}<{@link String}> */ public List getConfigAttributes() { @@ -72,7 +71,7 @@ public class FilterInvocationDefinitionSourceMapping { /** * Add a {@link ConfigAttribute} as {@link String} - * + * * @param configAttribute */ public void addConfigAttribute(String configAttribute) { diff --git a/core/src/main/java/org/acegisecurity/ldap/DefaultInitialDirContextFactory.java b/core/src/main/java/org/acegisecurity/ldap/DefaultInitialDirContextFactory.java index 27880f3d82..e18c2ee9c1 100644 --- a/core/src/main/java/org/acegisecurity/ldap/DefaultInitialDirContextFactory.java +++ b/core/src/main/java/org/acegisecurity/ldap/DefaultInitialDirContextFactory.java @@ -42,15 +42,19 @@ import javax.naming.directory.InitialDirContext; /** * Encapsulates the information for connecting to an LDAP server and provides an access point for obtaining - * DirContext references.

The directory location is configured using by setting the constructor argument + * DirContext references. + *

+ * The directory location is configured using by setting the constructor argument * providerUrl. This should be in the form ldap://monkeymachine.co.uk:389/dc=acegisecurity,dc=org. * The Sun JNDI provider also supports lists of space-separated URLs, each of which will be tried in turn until a - * connection is obtained.

- *

To obtain an initial context, the client calls the newInitialDirContext method. There are two - * signatures - one with no arguments and one which allows binding with a specific username and password.

- *

The no-args version will bind anonymously unless a manager login has been configured using the properties + * connection is obtained. + *

+ *

To obtain an initial context, the client calls the newInitialDirContext method. There are two + * signatures - one with no arguments and one which allows binding with a specific username and password. + *

+ *

The no-args version will bind anonymously unless a manager login has been configured using the properties * managerDn and managerPassword, in which case it will bind as the manager user.

- *

Connection pooling is enabled by default for anonymous or manager connections, but not when binding as a + *

Connection pooling is enabled by default for anonymous or manager connections, but not when binding as a * specific user.

* * @author Robert Sanders @@ -113,7 +117,7 @@ public class DefaultInitialDirContextFactory implements InitialDirContextFactory /** * Create and initialize an instance to the LDAP url provided - * + * * @param providerUrl a String of the form ldap://localhost:389/base_dn */ public DefaultInitialDirContextFactory(String providerUrl) { @@ -124,7 +128,7 @@ public class DefaultInitialDirContextFactory implements InitialDirContextFactory /** * Set the LDAP url - * + * * @param providerUrl a String of the form ldap://localhost:389/base_dn */ private void setProviderUrl(String providerUrl) { @@ -154,7 +158,7 @@ public class DefaultInitialDirContextFactory implements InitialDirContextFactory /** * Get the LDAP url - * + * * @return the url */ private String getProviderUrl() { @@ -175,8 +179,8 @@ public class DefaultInitialDirContextFactory implements InitialDirContextFactory try { return useLdapContext ? new InitialLdapContext(env, null) : new InitialDirContext(env); } catch (NamingException ne) { - if ((ne instanceof javax.naming.AuthenticationException) || - (ne instanceof OperationNotSupportedException)) { + if ((ne instanceof javax.naming.AuthenticationException) + || (ne instanceof OperationNotSupportedException)) { throw new BadCredentialsException(messages.getMessage("DefaultIntitalDirContextFactory.badCredentials", "Bad credentials"), ne); } diff --git a/core/src/main/java/org/acegisecurity/ldap/LdapCallback.java b/core/src/main/java/org/acegisecurity/ldap/LdapCallback.java index 868c3ae5ae..b0b9d05b25 100644 --- a/core/src/main/java/org/acegisecurity/ldap/LdapCallback.java +++ b/core/src/main/java/org/acegisecurity/ldap/LdapCallback.java @@ -27,6 +27,6 @@ import javax.naming.directory.DirContext; public interface LdapCallback { //~ Methods ======================================================================================================== - public Object doInDirContext(DirContext dirContext) + Object doInDirContext(DirContext dirContext) throws NamingException; } diff --git a/core/src/main/java/org/acegisecurity/ldap/LdapEntryMapper.java b/core/src/main/java/org/acegisecurity/ldap/LdapEntryMapper.java index 5a906d4fcc..d787fc3d16 100644 --- a/core/src/main/java/org/acegisecurity/ldap/LdapEntryMapper.java +++ b/core/src/main/java/org/acegisecurity/ldap/LdapEntryMapper.java @@ -19,16 +19,16 @@ import javax.naming.NamingException; import javax.naming.directory.Attributes; -/** - * A mapper for use with {@link LdapTemplate}. Creates a customized object from - * a set of attributes retrieved from a directory entry. - * - * @author Luke Taylor - * @version $Id$ +/** + * A mapper for use with {@link LdapTemplate}. Creates a customized object from + * a set of attributes retrieved from a directory entry. + * + * @author Luke Taylor + * @version $Id$ */ public interface LdapEntryMapper { //~ Methods ======================================================================================================== - public Object mapAttributes(String dn, Attributes attributes) + Object mapAttributes(String dn, Attributes attributes) throws NamingException; } diff --git a/core/src/main/java/org/acegisecurity/ldap/LdapTemplate.java b/core/src/main/java/org/acegisecurity/ldap/LdapTemplate.java index a469df5c65..ae7afd9b68 100644 --- a/core/src/main/java/org/acegisecurity/ldap/LdapTemplate.java +++ b/core/src/main/java/org/acegisecurity/ldap/LdapTemplate.java @@ -238,7 +238,8 @@ public class LdapTemplate { * * @return the object created by the mapper from the matching entry * - * @throws IncorrectResultSizeDataAccessException if no results are found or the search returns more than one result. + * @throws IncorrectResultSizeDataAccessException if no results are found or the search returns more than one + * result. */ public Object searchForSingleEntry(final String base, final String filter, final Object[] params, final LdapEntryMapper mapper) { diff --git a/core/src/main/java/org/acegisecurity/ldap/LdapUtils.java b/core/src/main/java/org/acegisecurity/ldap/LdapUtils.java index 39641477d3..81f25c1b29 100644 --- a/core/src/main/java/org/acegisecurity/ldap/LdapUtils.java +++ b/core/src/main/java/org/acegisecurity/ldap/LdapUtils.java @@ -32,11 +32,16 @@ import javax.naming.NamingException; * @author Luke Taylor * @version $Id$ */ -public class LdapUtils { +public final class LdapUtils { //~ Static fields/initializers ===================================================================================== private static final Log logger = LogFactory.getLog(LdapUtils.class); + //~ Constructors =================================================================================================== + + private LdapUtils() { + } + //~ Methods ======================================================================================================== public static void closeContext(Context ctx) { diff --git a/core/src/main/java/org/acegisecurity/ldap/search/FilterBasedLdapUserSearch.java b/core/src/main/java/org/acegisecurity/ldap/search/FilterBasedLdapUserSearch.java index 8d30994938..0b5bc55200 100644 --- a/core/src/main/java/org/acegisecurity/ldap/search/FilterBasedLdapUserSearch.java +++ b/core/src/main/java/org/acegisecurity/ldap/search/FilterBasedLdapUserSearch.java @@ -124,7 +124,7 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch { return user.createUserDetails(); } catch (IncorrectResultSizeDataAccessException notFound) { - if(notFound.getActualSize() == 0) { + if (notFound.getActualSize() == 0) { throw new UsernameNotFoundException("User " + username + " not found in directory."); } // Search should never return multiple results if properly configured, so just rethrow diff --git a/core/src/main/java/org/acegisecurity/providers/AuthenticationProvider.java b/core/src/main/java/org/acegisecurity/providers/AuthenticationProvider.java index 9e875bdfca..a1cf9324ef 100644 --- a/core/src/main/java/org/acegisecurity/providers/AuthenticationProvider.java +++ b/core/src/main/java/org/acegisecurity/providers/AuthenticationProvider.java @@ -42,17 +42,20 @@ public interface AuthenticationProvider { * * @throws AuthenticationException if authentication fails. */ - public Authentication authenticate(Authentication authentication) + Authentication authenticate(Authentication authentication) throws AuthenticationException; /** * Returns true if this AuthenticationProvider supports the indicated - * Authentication object.

Returning true does not guarantee an - * AuthenticationProvider will be able to authenticate the presented instance of the - * Authentication class. It simply indicates it can support closer evaluation of it. An - * AuthenticationProvider can still return null from the {@link - * #authenticate(Authentication)} method to indicate another AuthenticationProvider should be tried.

- *

Selection of an AuthenticationProvider capable of performing authentication is + * Authentication object. + *

+ * Returning true does not guarantee an AuthenticationProvider will be able to + * authenticate the presented instance of the Authentication class. It simply indicates it can support + * closer evaluation of it. An AuthenticationProvider can still return null from the + * {@link #authenticate(Authentication)} method to indicate another AuthenticationProvider should be + * tried. + *

+ *

Selection of an AuthenticationProvider capable of performing authentication is * conducted at runtime the ProviderManager.

* * @param authentication DOCUMENT ME! @@ -60,5 +63,5 @@ public interface AuthenticationProvider { * @return true if the implementation can more closely evaluate the Authentication class * presented */ - public boolean supports(Class authentication); + boolean supports(Class authentication); } diff --git a/core/src/main/java/org/acegisecurity/providers/ProviderManager.java b/core/src/main/java/org/acegisecurity/providers/ProviderManager.java index 5c29c57b2c..f7ef360911 100644 --- a/core/src/main/java/org/acegisecurity/providers/ProviderManager.java +++ b/core/src/main/java/org/acegisecurity/providers/ProviderManager.java @@ -69,17 +69,22 @@ import java.util.Properties; /** - * Iterates an {@link Authentication} request through a list of {@link AuthenticationProvider}s. Can optionally be - * configured with a {@link ConcurrentSessionController} to limit the number of sessions a user can have.

AuthenticationProviders - * are tried in order until one provides a non-null response. A non-null response indicates the provider had authority - * to decide on the authentication request and no further providers are tried. If an - * AuthenticationException is thrown by a provider, it is retained until subsequent providers are tried. - * If a subsequent provider successfully authenticates the request, the earlier authentication exception is - * disregarded and the successful authentication will be used. If no subsequent provider provides a non-null response, - * or a new AuthenticationException, the last AuthenticationException received will be used. - * If no provider returns a non-null response, or indicates it can even process an Authentication, the - * ProviderManager will throw a ProviderNotFoundException.

- *

If a valid Authentication is returned by an AuthenticationProvider, the + * Iterates an {@link Authentication} request through a list of {@link AuthenticationProvider}s. + * + * Can optionally be configured with a {@link ConcurrentSessionController} to limit the number of sessions a user can + * have. + *

+ * AuthenticationProviders are tried in order until one provides a non-null response. + * A non-null response indicates the provider had authority to decide on the authentication request and no further + * providers are tried. If an AuthenticationException is thrown by a provider, it is retained until + * subsequent providers are tried. If a subsequent provider successfully authenticates the request, the earlier + * authentication exception is disregarded and the successful authentication will be used. If no subsequent provider + * provides a non-null response, or a new AuthenticationException, the last + * AuthenticationException received will be used. If no provider returns a non-null response, or indicates + * it can even process an Authentication, the ProviderManager will throw a + * ProviderNotFoundException.

+ * + *

If a valid Authentication is returned by an AuthenticationProvider, the * ProviderManager will publish an {@link * org.acegisecurity.event.authentication.AuthenticationSuccessEvent}. If an AuthenticationException is * detected, the final AuthenticationException thrown will be used to publish an appropriate failure @@ -108,23 +113,25 @@ public class ProviderManager extends AbstractAuthenticationManager implements In static { DEFAULT_EXCEPTION_MAPPINGS.put(AccountExpiredException.class.getName(), - AuthenticationFailureExpiredEvent.class.getName()); + AuthenticationFailureExpiredEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(AuthenticationServiceException.class.getName(), - AuthenticationFailureServiceExceptionEvent.class.getName()); - DEFAULT_EXCEPTION_MAPPINGS.put(LockedException.class.getName(), AuthenticationFailureLockedEvent.class.getName()); + AuthenticationFailureServiceExceptionEvent.class.getName()); + DEFAULT_EXCEPTION_MAPPINGS.put(LockedException.class.getName(), + AuthenticationFailureLockedEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(CredentialsExpiredException.class.getName(), - AuthenticationFailureCredentialsExpiredEvent.class.getName()); - DEFAULT_EXCEPTION_MAPPINGS.put(DisabledException.class.getName(), AuthenticationFailureDisabledEvent.class.getName()); + AuthenticationFailureCredentialsExpiredEvent.class.getName()); + DEFAULT_EXCEPTION_MAPPINGS.put(DisabledException.class.getName(), + AuthenticationFailureDisabledEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(BadCredentialsException.class.getName(), - AuthenticationFailureBadCredentialsEvent.class.getName()); + AuthenticationFailureBadCredentialsEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(UsernameNotFoundException.class.getName(), - AuthenticationFailureBadCredentialsEvent.class.getName()); + AuthenticationFailureBadCredentialsEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(ConcurrentLoginException.class.getName(), - AuthenticationFailureConcurrentLoginEvent.class.getName()); + AuthenticationFailureConcurrentLoginEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(ProviderNotFoundException.class.getName(), - AuthenticationFailureProviderNotFoundEvent.class.getName()); + AuthenticationFailureProviderNotFoundEvent.class.getName()); DEFAULT_EXCEPTION_MAPPINGS.put(ProxyUntrustedException.class.getName(), - AuthenticationFailureProxyUntrustedEvent.class.getName()); + AuthenticationFailureProxyUntrustedEvent.class.getName()); } public ProviderManager() { @@ -274,7 +281,8 @@ public class ProviderManager extends AbstractAuthenticationManager implements In while (iter.hasNext()) { Object currentObject = iter.next(); - Assert.isInstanceOf(AuthenticationProvider.class, currentObject, "Can only provide AuthenticationProvider instances"); + Assert.isInstanceOf(AuthenticationProvider.class, currentObject, + "Can only provide AuthenticationProvider instances"); } this.providers = newList; @@ -290,9 +298,9 @@ public class ProviderManager extends AbstractAuthenticationManager implements In this.sessionController = sessionController; } - private void publishEvent( ApplicationEvent event ) { - if ( applicationEventPublisher != null ) { - applicationEventPublisher.publishEvent( event ); + private void publishEvent(ApplicationEvent event) { + if (applicationEventPublisher != null) { + applicationEventPublisher.publishEvent(event); } } } diff --git a/core/src/main/java/org/acegisecurity/providers/TestingAuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/TestingAuthenticationToken.java index e22d05d448..001d3846c5 100644 --- a/core/src/main/java/org/acegisecurity/providers/TestingAuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/TestingAuthenticationToken.java @@ -28,7 +28,7 @@ import org.acegisecurity.GrantedAuthority; public class TestingAuthenticationToken extends AbstractAuthenticationToken { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Object credentials; private Object principal; diff --git a/core/src/main/java/org/acegisecurity/providers/UsernamePasswordAuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/UsernamePasswordAuthenticationToken.java index 28558f68b0..cb7ad7ce58 100644 --- a/core/src/main/java/org/acegisecurity/providers/UsernamePasswordAuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/UsernamePasswordAuthenticationToken.java @@ -30,7 +30,7 @@ import org.acegisecurity.GrantedAuthority; public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Object credentials; private Object principal; diff --git a/core/src/main/java/org/acegisecurity/providers/anonymous/AnonymousAuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/anonymous/AnonymousAuthenticationToken.java index 420275104e..b382dae566 100644 --- a/core/src/main/java/org/acegisecurity/providers/anonymous/AnonymousAuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/anonymous/AnonymousAuthenticationToken.java @@ -31,7 +31,7 @@ import java.io.Serializable; public class AnonymousAuthenticationToken extends AbstractAuthenticationToken implements Serializable { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Object principal; private int keyHash; diff --git a/core/src/main/java/org/acegisecurity/providers/cas/CasAuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/cas/CasAuthenticationToken.java index 95b8b16d5a..f3ebb90ec5 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/CasAuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/CasAuthenticationToken.java @@ -35,7 +35,7 @@ import java.util.List; public class CasAuthenticationToken extends AbstractAuthenticationToken implements Serializable { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private final List proxyList; private final Object credentials; private final Object principal; diff --git a/core/src/main/java/org/acegisecurity/providers/cas/CasAuthoritiesPopulator.java b/core/src/main/java/org/acegisecurity/providers/cas/CasAuthoritiesPopulator.java index 05506320fd..f58aa42708 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/CasAuthoritiesPopulator.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/CasAuthoritiesPopulator.java @@ -23,16 +23,16 @@ import org.acegisecurity.userdetails.UserDetails; /** * Populates the UserDetails associated with a CAS authenticated * user. - * - *

+ * + *

* CAS does not provide the authorities (roles) granted to a user. It merely * authenticates their identity. As the Acegi Security System for Spring needs * to know the authorities granted to a user in order to construct a valid * Authentication object, implementations of this interface will * provide this information. *

- * - *

+ * + *

* A {@link UserDetails} is returned by implementations. The * UserDetails must, at minimum, contain the username and * GrantedAuthority[] objects applicable to the CAS-authenticated @@ -43,8 +43,8 @@ import org.acegisecurity.userdetails.UserDetails; * generated CasAuthenticationToken, so additional properties * such as email addresses, telephone numbers etc can easily be stored. *

- * - *

+ * + *

* Implementations should not perform any caching. They will only be called * when a refresh is required. *

@@ -65,6 +65,6 @@ public interface CasAuthoritiesPopulator { * * @throws AuthenticationException DOCUMENT ME! */ - public UserDetails getUserDetails(String casUserId) + UserDetails getUserDetails(String casUserId) throws AuthenticationException; } diff --git a/core/src/main/java/org/acegisecurity/providers/cas/CasProxyDecider.java b/core/src/main/java/org/acegisecurity/providers/cas/CasProxyDecider.java index eb893a932b..b4ae9fd945 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/CasProxyDecider.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/CasProxyDecider.java @@ -20,8 +20,8 @@ import java.util.List; /** * Decides whether a proxy list presented via CAS is trusted or not. - * - *

+ * + *

* CAS 1.0 allowed services to receive a service ticket and then validate it. * CAS 2.0 allows services to receive a service ticket and then validate it * with a proxy callback URL. The callback will enable the CAS server to @@ -30,22 +30,22 @@ import java.util.List; * internal record that a proxy-granting ticket is due to be received via the * callback URL. *

- * - *

+ * + *

* With a proxy-granting ticket, a service can request the CAS server provides * it with a proxy ticket. A proxy ticket is just a service ticket, but the * CAS server internally tracks the list (chain) of services used to build the * proxy ticket. The proxy ticket is then presented to the target service. *

- * - *

+ * + *

* If this application is a target service of a proxy ticket, the * CasProxyDecider resolves whether or not the proxy list is * trusted. Applications should only trust services they allow to impersonate * an end user. *

- * - *

+ * + *

* If this application is a service that should never accept proxy-granting * tickets, the implementation should reject tickets that present a proxy list * with any members. If the list has no members, it indicates the CAS server @@ -60,13 +60,14 @@ public interface CasProxyDecider { //~ Methods ======================================================================================================== /** - * Decides whether the proxy list is trusted.

Must throw any ProxyUntrustedException if the + * Decides whether the proxy list is trusted. + *

Must throw any ProxyUntrustedException if the * proxy list is untrusted.

* - * @param proxyList DOCUMENT ME! + * @param proxyList the list of proxies to be checked. * * @throws ProxyUntrustedException DOCUMENT ME! */ - public void confirmProxyListTrusted(List proxyList) + void confirmProxyListTrusted(List proxyList) throws ProxyUntrustedException; } diff --git a/core/src/main/java/org/acegisecurity/providers/cas/StatelessTicketCache.java b/core/src/main/java/org/acegisecurity/providers/cas/StatelessTicketCache.java index 1149d842e6..8f67eb1955 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/StatelessTicketCache.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/StatelessTicketCache.java @@ -17,7 +17,7 @@ package org.acegisecurity.providers.cas; /** * Caches CAS service tickets and CAS proxy tickets for stateless connections. - * + * *

* When a service ticket or proxy ticket is validated against the CAS server, * it is unable to be used again. Most types of callers are stateful and are @@ -26,14 +26,14 @@ package org.acegisecurity.providers.cas; * HttpSession, meaning the removal of the ticket from the CAS * server is not an issue. *

- * + * *

* Stateless callers, such as remoting protocols, cannot take advantage of * HttpSession. If the stateless caller is located a significant * network distance from the CAS server, acquiring a fresh service ticket or * proxy ticket for each invocation would be expensive. *

- * + * *

* To avoid this issue with stateless callers, it is expected stateless callers * will obtain a single service ticket or proxy ticket, and then present this @@ -41,7 +41,7 @@ package org.acegisecurity.providers.cas; * occasion. As no HttpSession is available for such callers, the * affirmative CAS validation outcome cannot be stored in this location. *

- * + * *

* The StatelessTicketCache enables the service tickets and proxy * tickets belonging to stateless callers to be placed in a cache. This @@ -49,7 +49,7 @@ package org.acegisecurity.providers.cas; * providing the same capability as a HttpSession with the ticket * identifier being the key rather than a session identifier. *

- * + * *

* Implementations should provide a reasonable timeout on stored entries, such * that the stateless caller are not required to unnecessarily acquire fresh @@ -65,7 +65,7 @@ public interface StatelessTicketCache { /** * Retrieves the CasAuthenticationToken associated with the * specified ticket. - * + * *

* If not found, returns a * nullCasAuthenticationToken. @@ -73,11 +73,11 @@ public interface StatelessTicketCache { * * @return the fully populated authentication token */ - public CasAuthenticationToken getByTicketId(String serviceTicket); + CasAuthenticationToken getByTicketId(String serviceTicket); /** * Adds the specified CasAuthenticationToken to the cache. - * + * *

* The {@link CasAuthenticationToken#getCredentials()} method is used to * retrieve the service ticket number. @@ -85,12 +85,12 @@ public interface StatelessTicketCache { * * @param token to be added to the cache */ - public void putTicketInCache(CasAuthenticationToken token); + void putTicketInCache(CasAuthenticationToken token); /** * Removes the specified ticket from the cache, as per {@link * #removeTicketFromCache(String)}. - * + * *

* Implementations should use {@link * CasAuthenticationToken#getCredentials()} to obtain the ticket and then @@ -99,12 +99,12 @@ public interface StatelessTicketCache { * * @param token to be removed */ - public void removeTicketFromCache(CasAuthenticationToken token); + void removeTicketFromCache(CasAuthenticationToken token); /** * Removes the specified ticket from the cache, meaning that future calls * will require a new service ticket. - * + * *

* This is in case applications wish to provide a session termination * capability for their stateless clients. @@ -112,5 +112,5 @@ public interface StatelessTicketCache { * * @param serviceTicket to be removed */ - public void removeTicketFromCache(String serviceTicket); + void removeTicketFromCache(String serviceTicket); } diff --git a/core/src/main/java/org/acegisecurity/providers/cas/TicketValidator.java b/core/src/main/java/org/acegisecurity/providers/cas/TicketValidator.java index 8363c2cb97..07b9882f46 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/TicketValidator.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/TicketValidator.java @@ -20,14 +20,14 @@ import org.acegisecurity.AuthenticationException; /** * Validates a CAS service ticket. - * - *

+ * + *

* Implementations must accept CAS proxy tickets, in addition to CAS service * tickets. If proxy tickets should be rejected, this is resolved by a {@link * CasProxyDecider} implementation (not by the TicketValidator). *

- * - *

+ * + *

* Implementations may request a proxy granting ticket if wish, although this * behaviour is not mandatory. *

@@ -48,6 +48,6 @@ public interface TicketValidator { * * @throws AuthenticationException DOCUMENT ME! */ - public TicketResponse confirmTicketValid(String serviceTicket) + TicketResponse confirmTicketValid(String serviceTicket) throws AuthenticationException; } diff --git a/core/src/main/java/org/acegisecurity/providers/cas/proxy/RejectProxyTickets.java b/core/src/main/java/org/acegisecurity/providers/cas/proxy/RejectProxyTickets.java index aa97e2a0c8..4f28cb9051 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/proxy/RejectProxyTickets.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/proxy/RejectProxyTickets.java @@ -66,7 +66,8 @@ public class RejectProxyTickets implements CasProxyDecider, MessageSourceAware, logger.debug("Proxies are unacceptable; proxy list provided: " + proxyList.toString()); } - throw new ProxyUntrustedException(messages.getMessage("RejectProxyTickets.reject", "Proxy tickets are rejected")); + throw new ProxyUntrustedException( + messages.getMessage("RejectProxyTickets.reject", "Proxy tickets are rejected")); } public void setMessageSource(MessageSource messageSource) { diff --git a/core/src/main/java/org/acegisecurity/providers/cas/ticketvalidator/CasProxyTicketValidator.java b/core/src/main/java/org/acegisecurity/providers/cas/ticketvalidator/CasProxyTicketValidator.java index c5348b74e1..50ca127122 100644 --- a/core/src/main/java/org/acegisecurity/providers/cas/ticketvalidator/CasProxyTicketValidator.java +++ b/core/src/main/java/org/acegisecurity/providers/cas/ticketvalidator/CasProxyTicketValidator.java @@ -55,7 +55,9 @@ public class CasProxyTicketValidator extends AbstractTicketValidator { if (super.getServiceProperties().isSendRenew()) { logger.warn( - "The current CAS ProxyTicketValidator does not support the 'renew' property. The ticket cannot be validated as having been issued by a 'renew' authentication. It is expected this will be corrected in a future version of CAS' ProxyTicketValidator."); + "The current CAS ProxyTicketValidator does not support the 'renew' property. " + + "The ticket cannot be validated as having been issued by a 'renew' authentication. " + + "It is expected this will be corrected in a future version of CAS' ProxyTicketValidator."); } if ((this.proxyCallbackUrl != null) && (!"".equals(this.proxyCallbackUrl))) { @@ -66,11 +68,13 @@ public class CasProxyTicketValidator extends AbstractTicketValidator { } /** - * Optional callback URL to obtain a proxy-granting ticket from CAS.

This callback URL belongs to the - * Acegi Security System for Spring secured application. We suggest you use CAS' ProxyTicketReceptor - * servlet to receive this callback and manage the proxy-granting ticket list. The callback URL is usually - * something like https://www.mycompany.com/application/casProxy/receptor.

- *

If left null, the CasAuthenticationToken will not have a proxy granting + * Optional callback URL to obtain a proxy-granting ticket from CAS. + *

This callback URL belongs to the Acegi Security System for Spring secured application. We suggest you use + * CAS' ProxyTicketReceptor servlet to receive this callback and manage the proxy-granting ticket list. + * The callback URL is usually something like + * https://www.mycompany.com/application/casProxy/receptor. + *

+ *

If left null, the CasAuthenticationToken will not have a proxy granting * ticket IOU and there will be no proxy-granting ticket callback. Accordingly, the Acegi Securty System for * Spring secured application will be unable to obtain a proxy ticket to call another CAS-secured service on * behalf of the user. This is not really an issue for most applications.

diff --git a/core/src/main/java/org/acegisecurity/providers/dao/AbstractUserDetailsAuthenticationProvider.java b/core/src/main/java/org/acegisecurity/providers/dao/AbstractUserDetailsAuthenticationProvider.java index ae109ed193..c37520a0b1 100644 --- a/core/src/main/java/org/acegisecurity/providers/dao/AbstractUserDetailsAuthenticationProvider.java +++ b/core/src/main/java/org/acegisecurity/providers/dao/AbstractUserDetailsAuthenticationProvider.java @@ -44,15 +44,19 @@ import org.springframework.util.Assert; /** * A base {@link AuthenticationProvider} that allows subclasses to override and work with {@link * org.acegisecurity.userdetails.UserDetails} objects. The class is designed to respond to {@link - * UsernamePasswordAuthenticationToken} authentication requests.

Upon successful validation, a - * UsernamePasswordAuthenticationToken will be created and returned to the caller. The token will include - * as its principal either a String representation of the username, or the {@link UserDetails} that was - * returned from the authentication repository. Using String is appropriate if a container adapter is - * being used, as it expects String representations of the username. Using UserDetails is - * appropriate if you require access to additional properties of the authenticated user, such as email addresses, - * human-friendly names etc. As container adapters are not recommended to be used, and UserDetails - * implementations provide additional flexibility, by default a UserDetails is returned. To override this - * default, set the {@link #setForcePrincipalAsString} to true.

+ * UsernamePasswordAuthenticationToken} authentication requests. + * + *

+ * Upon successful validation, a UsernamePasswordAuthenticationToken will be created and returned to the + * caller. The token will include as its principal either a String representation of the username, or the + * {@link UserDetails} that was returned from the authentication repository. Using String is appropriate + * if a container adapter is being used, as it expects String representations of the username. + * Using UserDetails is appropriate if you require access to additional properties of the authenticated + * user, such as email addresses, human-friendly names etc. As container adapters are not recommended to be used, + * and UserDetails implementations provide additional flexibility, by default a UserDetails + * is returned. To override this + * default, set the {@link #setForcePrincipalAsString} to true. + *

*

Caching is handled via the UserDetails object being placed in the {@link UserCache}. This * ensures that subsequent requests with the same username can be validated without needing to query the {@link * UserDetailsService}. It should be noted that if a user appears to present an incorrect password, the {@link @@ -145,15 +149,15 @@ public abstract class AbstractUserDetailsAuthenticationProvider implements Authe try { additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } catch (AuthenticationException exception) { - if(cacheWasUsed) { + if (cacheWasUsed) { // There was a problem, so try again after checking - // we're using latest data (ie not from the cache) + // we're using latest data (ie not from the cache) cacheWasUsed = false; user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); - } else { - throw exception; - } + } else { + throw exception; + } } if (!user.isCredentialsNonExpired()) { diff --git a/core/src/main/java/org/acegisecurity/providers/dao/DaoAuthenticationProvider.java b/core/src/main/java/org/acegisecurity/providers/dao/DaoAuthenticationProvider.java index fffd4e53a5..3da097ad44 100644 --- a/core/src/main/java/org/acegisecurity/providers/dao/DaoAuthenticationProvider.java +++ b/core/src/main/java/org/acegisecurity/providers/dao/DaoAuthenticationProvider.java @@ -57,9 +57,11 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication salt = this.saltSource.getSalt(userDetails); } - if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), authentication.getCredentials().toString(), salt)) { + if (!passwordEncoder.isPasswordValid( + userDetails.getPassword(), authentication.getCredentials().toString(), salt)) { throw new BadCredentialsException(messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null); + "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), + includeDetailsObject ? userDetails : null); } } @@ -122,11 +124,11 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication this.userDetailsService = userDetailsService; } - public boolean isIncludeDetailsObject() { - return includeDetailsObject; - } + public boolean isIncludeDetailsObject() { + return includeDetailsObject; + } - public void setIncludeDetailsObject(boolean includeDetailsObject) { - this.includeDetailsObject = includeDetailsObject; - } + public void setIncludeDetailsObject(boolean includeDetailsObject) { + this.includeDetailsObject = includeDetailsObject; + } } diff --git a/core/src/main/java/org/acegisecurity/providers/dao/SaltSource.java b/core/src/main/java/org/acegisecurity/providers/dao/SaltSource.java index a7f1aa6a8e..83fbb60e5b 100644 --- a/core/src/main/java/org/acegisecurity/providers/dao/SaltSource.java +++ b/core/src/main/java/org/acegisecurity/providers/dao/SaltSource.java @@ -34,5 +34,5 @@ public interface SaltSource { * * @return the salt to use for this UserDetails */ - public Object getSalt(UserDetails user); + Object getSalt(UserDetails user); } diff --git a/core/src/main/java/org/acegisecurity/providers/dao/UserCache.java b/core/src/main/java/org/acegisecurity/providers/dao/UserCache.java index 4b3ee4e4a7..77b911e5f0 100644 --- a/core/src/main/java/org/acegisecurity/providers/dao/UserCache.java +++ b/core/src/main/java/org/acegisecurity/providers/dao/UserCache.java @@ -21,7 +21,7 @@ import org.acegisecurity.userdetails.UserDetails; /** * Provides a cache of {@link User} objects. - * + * *

* Implementations should provide appropriate methods to set their cache * parameters (eg time-to-live) and/or force removal of entities before their @@ -44,7 +44,7 @@ public interface UserCache { * @return the populated UserDetails or null if the user could not be found or if the * cache entry has expired */ - public UserDetails getUserFromCache(String username); + UserDetails getUserFromCache(String username); /** * Places a {@link UserDetails} in the cache. The username is the key used to subsequently @@ -52,7 +52,7 @@ public interface UserCache { * * @param user the fully populated UserDetails to place in the cache */ - public void putUserInCache(UserDetails user); + void putUserInCache(UserDetails user); /** * Removes the specified user from the cache. The username is the key used to remove the user. @@ -62,5 +62,5 @@ public interface UserCache { * * @param username to be evicted from the cache */ - public void removeUserFromCache(String username); + void removeUserFromCache(String username); } diff --git a/core/src/main/java/org/acegisecurity/providers/encoding/MessageDigestPasswordEncoder.java b/core/src/main/java/org/acegisecurity/providers/encoding/MessageDigestPasswordEncoder.java index 4e98a83b2c..920d31659a 100644 --- a/core/src/main/java/org/acegisecurity/providers/encoding/MessageDigestPasswordEncoder.java +++ b/core/src/main/java/org/acegisecurity/providers/encoding/MessageDigestPasswordEncoder.java @@ -7,20 +7,25 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** - *

Base for digest password encoders.

- * This class can be used stand-alone, or one of the subclasses can be used for compatiblity and convenience - *

When using this class directly you must specify a + * Base for digest password encoders. + *

This class can be used stand-alone, or one of the subclasses can be used for compatiblity and convenience. + * When using this class directly you must specify a * * Message Digest Algorithm to use as a constructor arg

* - * The encoded password hash is normally returned as Hex (32 char) version of the hash bytes. Setting the encodeHashAsBase64 - * property to true will cause the encoded pass to be returned as Base64 text, which will consume 24 characters. See {@link BaseDigestPasswordEncoder#setEncodeHashAsBase64(boolean)} - *
+ *

The encoded password hash is normally returned as Hex (32 char) version of the hash bytes. + * Setting the encodeHashAsBase64 property to true will cause the encoded pass to be returned + * as Base64 text, which will consume 24 characters. + * See {@link BaseDigestPasswordEncoder#setEncodeHashAsBase64(boolean)} + *

+ *

* This PasswordEncoder can be used directly as in the following example:
- * <bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.MessageDigestPasswordEncoder">
- *   <constructor-arg value="MD5"/>
+ *

+ * <bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.MessageDigestPasswordEncoder">
+ *     <constructor-arg value="MD5"/>
  * </bean>
- *
+ * 
+ *

* * @author Ray Krueger * @since 1.0.1 @@ -87,8 +92,7 @@ public class MessageDigestPasswordEncoder extends BaseDigestPasswordEncoder { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { - throw new IllegalArgumentException("No such algorithm [" + - algorithm + "]"); + throw new IllegalArgumentException("No such algorithm [" + algorithm + "]"); } } diff --git a/core/src/main/java/org/acegisecurity/providers/encoding/PasswordEncoder.java b/core/src/main/java/org/acegisecurity/providers/encoding/PasswordEncoder.java index b4b360fde0..136353dced 100644 --- a/core/src/main/java/org/acegisecurity/providers/encoding/PasswordEncoder.java +++ b/core/src/main/java/org/acegisecurity/providers/encoding/PasswordEncoder.java @@ -52,7 +52,7 @@ public interface PasswordEncoder { * * @throws DataAccessException DOCUMENT ME! */ - public String encodePassword(String rawPass, Object salt) + String encodePassword(String rawPass, Object salt) throws DataAccessException; /** @@ -71,6 +71,6 @@ public interface PasswordEncoder { * * @throws DataAccessException DOCUMENT ME! */ - public boolean isPasswordValid(String encPass, String rawPass, Object salt) + boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException; } diff --git a/core/src/main/java/org/acegisecurity/providers/encoding/ShaPasswordEncoder.java b/core/src/main/java/org/acegisecurity/providers/encoding/ShaPasswordEncoder.java index e481e00645..9145c9dcd3 100644 --- a/core/src/main/java/org/acegisecurity/providers/encoding/ShaPasswordEncoder.java +++ b/core/src/main/java/org/acegisecurity/providers/encoding/ShaPasswordEncoder.java @@ -18,16 +18,17 @@ package org.acegisecurity.providers.encoding; *

SHA implementation of PasswordEncoder.

*

If a null password is presented, it will be treated as an empty String ("") * password.

- *

As SHA is a one-way hash, the salt can contain any characters.

- * - * The default strength for the SHA encoding is SHA-1. If you wish to use higher strengths use the argumented constructor. + *

As SHA is a one-way hash, the salt can contain any characters. The default strength for the SHA encoding is SHA-1. + * If you wish to use higher strengths use the argumented constructor. * {@link #ShaPasswordEncoder(int strength)} - *
- * The applicationContext example...
- * <bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.ShaPasswordEncoder">
- *   <constructor-arg value="256"/>
+ *

+ *

+ * The applicationContext example... + *

+ * <bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.ShaPasswordEncoder">
+ *     <constructor-arg value="256"/>
  * </bean>
- *
+ * 
* * @author Ray Krueger * @author colin sampaleanu diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/AuthorityGranter.java b/core/src/main/java/org/acegisecurity/providers/jaas/AuthorityGranter.java index 64479bf433..25db4240b1 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/AuthorityGranter.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/AuthorityGranter.java @@ -23,7 +23,7 @@ import java.util.Set; /** * The AuthorityGranter interface is used to map a given principal to role * names. - * + * *

* If a Windows NT login module were to be used from JAAS, an AuthrityGranter * implementation could be created to map a NT Group Principal to a ROLE_USER @@ -48,5 +48,5 @@ public interface AuthorityGranter { * * @return A java.util.Set of role names to grant, or null meaning no roles should be granted for the principal. */ - public Set grant(Principal principal); + Set grant(Principal principal); } diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationCallbackHandler.java b/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationCallbackHandler.java index b1b5d975d8..3ff925cbdf 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationCallbackHandler.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationCallbackHandler.java @@ -29,7 +29,7 @@ import javax.security.auth.callback.UnsupportedCallbackException; * handle method. The JaasAuthenticationCallbackHandler is only asked to * handle one Callback instance at at time rather than an array of all * Callbacks, as the javax... CallbackHandler defines. - * + * *

* Before a JaasAuthenticationCallbackHandler is asked to 'handle' any * callbacks, it is first passed the Authentication object that the login @@ -44,8 +44,8 @@ import javax.security.auth.callback.UnsupportedCallbackException; * @see JaasPasswordCallbackHandler * @see Callback - * @see CallbackHandler + * @see + * CallbackHandler */ public interface JaasAuthenticationCallbackHandler { //~ Methods ======================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationProvider.java b/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationProvider.java index 6c61009bcc..e51733dd19 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationProvider.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationProvider.java @@ -64,49 +64,78 @@ import javax.security.auth.login.LoginException; /** - * An {@link AuthenticationProvider} implementation that retrieves user details from a JAAS login configuration.

This - * AuthenticationProvider is capable of validating {@link + * An {@link AuthenticationProvider} implementation that retrieves user details from a JAAS login configuration. + * + *

This AuthenticationProvider is capable of validating {@link * org.acegisecurity.providers.UsernamePasswordAuthenticationToken} requests contain the correct username and * password.

- *

This implementation is backed by a This implementation is backed by a JAAS configuration. The * loginConfig property must be set to a given JAAS configuration file. This setter accepts a Spring {@link * org.springframework.core.io.Resource} instance. It should point to a JAAS configuration file containing an index - * matching the {@link #setLoginContextName(java.lang.String) loginContextName} property.

- *

For example: If this JaasAuthenticationProvider were configured in a Spring WebApplicationContext the xml to - * set the loginConfiguration could be as follows...

 <property name="loginConfig">
- *  <value>/WEB-INF/login.conf</value> </property> 

- *

The loginContextName should coincide with a given index in the loginConfig specifed. The loginConfig file - * used in the JUnit tests appears as the following...

 JAASTest {
- *  org.acegisecurity.providers.jaas.TestLoginModule required; }; 
Using the example login configuration - * above, the loginContextName property would be set as JAASTest...
- *  <property name="loginContextName"> <value>JAASTest</value> </property> 

- *

When using JAAS login modules as the authentication source, sometimes the LoginContext will - * require CallbackHandlers. The JaasAuthenticationProvider uses an internal CallbackHandler - * to wrap the {@link JaasAuthenticationCallbackHandler}s configured in the ApplicationContext. When the LoginContext - * calls the internal CallbackHandler, control is passed to each {@link JaasAuthenticationCallbackHandler} for each - * Callback passed.

- *

{{@link JaasAuthenticationCallbackHandler}s are passed to the JaasAuthenticationProvider through the {@link + * matching the {@link #setLoginContextName(java.lang.String) loginContextName} property. + *

+ *

+ * For example: If this JaasAuthenticationProvider were configured in a Spring WebApplicationContext the xml to + * set the loginConfiguration could be as follows... + *

+ * <property name="loginConfig">
+ *   <value>/WEB-INF/login.conf</value>
+ * </property>
+ * 
+ *

+ *

+ * The loginContextName should coincide with a given index in the loginConfig specifed. The loginConfig file + * used in the JUnit tests appears as the following... + *

 JAASTest {
+ *   org.acegisecurity.providers.jaas.TestLoginModule required;
+ * };
+ * 
+ * Using the example login configuration above, the loginContextName property would be set as JAASTest... + *
+ *  <property name="loginContextName"> <value>JAASTest</value> </property>
+ * 
+ *

+ *

When using JAAS login modules as the authentication source, sometimes the + * LoginContext will + * require CallbackHandlers. The JaasAuthenticationProvider uses an internal + * CallbackHandler + * to wrap the {@link JaasAuthenticationCallbackHandler}s configured in the ApplicationContext. + * When the LoginContext calls the internal CallbackHandler, control is passed to each + * {@link JaasAuthenticationCallbackHandler} for each Callback passed. + *

+ *

{@link JaasAuthenticationCallbackHandler}s are passed to the JaasAuthenticationProvider through the {@link * #setCallbackHandlers(org.acegisecurity.providers.jaas.JaasAuthenticationCallbackHandler[]) callbackHandlers} - * property. }

 <property name="callbackHandlers"> <list>
- *  <bean class="org.acegisecurity.providers.jaas.TestCallbackHandler"/>
- *  <bean class="{@link JaasNameCallbackHandler org.acegisecurity.providers.jaas.JaasNameCallbackHandler}"/>
- *  <bean class="{@link JaasPasswordCallbackHandler org.acegisecurity.providers.jaas.JaasPasswordCallbackHandler}"/>
- *  </list> </property> 

- *

After calling LoginContext.login(), the JaasAuthenticationProvider will retrieve the returned Principals + * property. + *

+ * <property name="callbackHandlers">
+ *   <list>
+ *     <bean class="org.acegisecurity.providers.jaas.TestCallbackHandler"/>
+ *     <bean class="{@link JaasNameCallbackHandler org.acegisecurity.providers.jaas.JaasNameCallbackHandler}"/>
+ *     <bean class="{@link JaasPasswordCallbackHandler org.acegisecurity.providers.jaas.JaasPasswordCallbackHandler}"/>
+ *  </list>
+ * </property>
+ * 
+ *

+ *

+ * After calling LoginContext.login(), the JaasAuthenticationProvider will retrieve the returned Principals * from the Subject (LoginContext.getSubject().getPrincipals). Each returned principal is then passed to the * configured {@link AuthorityGranter}s. An AuthorityGranter is a mapping between a returned Principal, and a role * name. If an AuthorityGranter wishes to grant an Authorization a role, it returns that role name from it's {@link * AuthorityGranter#grant(java.security.Principal)} method. The returned role will be applied to the Authorization * object as a {@link GrantedAuthority}.

- *

AuthorityGranters are configured in spring xml as follows...

 <property name="authorityGranters">
- *  <list> <bean class="org.acegisecurity.providers.jaas.TestAuthorityGranter"/> </list>
- *  </property> 

- * A configuration note: The JaasAuthenticationProvider uses the security properites + *

AuthorityGranters are configured in spring xml as follows... + *

+ * <property name="authorityGranters">
+ *   <list>
+ *     <bean class="org.acegisecurity.providers.jaas.TestAuthorityGranter"/>
+ *   </list>
+ *  </property>
+ * 
+ * A configuration note: The JaasAuthenticationProvider uses the security properites * "e;login.config.url.X"e; to configure jaas. If you would like to customize the way Jaas gets configured, * create a subclass of this and override the {@link #configureJaas(Resource)} method. + *

* * @author Ray Krueger * @version $Id$ @@ -135,7 +164,10 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Initi configureJaas(loginConfig); Assert.notNull(Configuration.getConfiguration(), - "As per http://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html \"If a Configuration object was set via the Configuration.setConfiguration method, then that object is returned. Otherwise, a default Configuration object is returned\". Your JRE returned null to Configuration.getConfiguration()."); + "As per http://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html " + + "\"If a Configuration object was set via the Configuration.setConfiguration method, then that object is " + + "returned. Otherwise, a default Configuration object is returned\". Your JRE returned null to " + + "Configuration.getConfiguration()."); } /** @@ -298,8 +330,8 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Initi * @param event */ protected void handleLogout(HttpSessionDestroyedEvent event) { - SecurityContext context = (SecurityContext) event.getSession() - .getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY); + SecurityContext context = (SecurityContext) + event.getSession().getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY); if (context == null) { log.debug("The destroyed session has no SecurityContext"); diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationToken.java index 38937e6960..9589a65c53 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/JaasAuthenticationToken.java @@ -30,7 +30,7 @@ import javax.security.auth.login.LoginContext; public class JaasAuthenticationToken extends UsernamePasswordAuthenticationToken { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private transient LoginContext loginContext = null; //~ Constructors =================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/JaasGrantedAuthority.java b/core/src/main/java/org/acegisecurity/providers/jaas/JaasGrantedAuthority.java index 0ebde45f10..685a13cc3b 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/JaasGrantedAuthority.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/JaasGrantedAuthority.java @@ -32,7 +32,7 @@ import java.security.Principal; public class JaasGrantedAuthority extends GrantedAuthorityImpl { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Principal principal; //~ Constructors =================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/JaasPasswordCallbackHandler.java b/core/src/main/java/org/acegisecurity/providers/jaas/JaasPasswordCallbackHandler.java index fd3897495b..7a1f0141df 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/JaasPasswordCallbackHandler.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/JaasPasswordCallbackHandler.java @@ -33,8 +33,8 @@ import javax.security.auth.callback.UnsupportedCallbackException; * @version $Id$ * * @see Callback - * @see PasswordCallback + * @see + * PasswordCallback */ public class JaasPasswordCallbackHandler implements JaasAuthenticationCallbackHandler { //~ Methods ======================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/providers/jaas/LoginExceptionResolver.java b/core/src/main/java/org/acegisecurity/providers/jaas/LoginExceptionResolver.java index 884b952097..fb3b4aae8b 100644 --- a/core/src/main/java/org/acegisecurity/providers/jaas/LoginExceptionResolver.java +++ b/core/src/main/java/org/acegisecurity/providers/jaas/LoginExceptionResolver.java @@ -41,5 +41,5 @@ public interface LoginExceptionResolver { * * @return The AcegiSecurityException that the JaasAuthenticationProvider should throw. */ - public AcegiSecurityException resolveException(LoginException e); + AcegiSecurityException resolveException(LoginException e); } diff --git a/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java b/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java index c4a3a95526..8b59458ffb 100644 --- a/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java +++ b/core/src/main/java/org/acegisecurity/providers/ldap/LdapAuthenticationProvider.java @@ -65,7 +65,9 @@ import org.springframework.dao.DataAccessException; *

A custom implementation could obtain the roles from a completely different source, for example from a database. *

* - *

Configuration

A simple configuration might be as follows: + *

Configuration

+ * + * A simple configuration might be as follows: *
  *    <bean id="initialDirContextFactory" class="org.acegisecurity.providers.ldap.DefaultInitialDirContextFactory">
  *      <constructor-arg value="ldap://monkeymachine:389/dc=acegisecurity,dc=org"/>
@@ -124,11 +126,13 @@ public class LdapAuthenticationProvider extends AbstractUserDetailsAuthenticatio
 
     //~ Constructors ===================================================================================================
 
-	/**
+    /**
      * Create an initialized instance to the values passed as arguments
      *
-     * @param authenticator
-     * @param authoritiesPopulator
+     * @param authenticator the authentication strategy (bind, password comparison, etc)
+     *          to be used by this provider for authenticating users.
+     * @param authoritiesPopulator the strategy for obtaining the authorities for a given user after they've been
+     *          authenticated.
      */
     public LdapAuthenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authoritiesPopulator) {
         this.setAuthenticator(authenticator);
@@ -160,7 +164,8 @@ public class LdapAuthenticationProvider extends AbstractUserDetailsAuthenticatio
         throws AuthenticationException {
         if (!userDetails.getPassword().equals(authentication.getCredentials().toString())) {
             throw new BadCredentialsException(messages.getMessage(
-                    "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null);
+                    "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"),
+                    includeDetailsObject ? userDetails : null);
         }
     }
 
@@ -221,13 +226,12 @@ public class LdapAuthenticationProvider extends AbstractUserDetailsAuthenticatio
             throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
         }
     }
-    
+
     public boolean isIncludeDetailsObject() {
-		return includeDetailsObject;
-	}
-
-	public void setIncludeDetailsObject(boolean includeDetailsObject) {
-		this.includeDetailsObject = includeDetailsObject;
-	}
+        return includeDetailsObject;
+    }
 
+    public void setIncludeDetailsObject(boolean includeDetailsObject) {
+        this.includeDetailsObject = includeDetailsObject;
+    }
 }
diff --git a/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/BindAuthenticator.java b/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/BindAuthenticator.java
index 8ed909f68f..100c7e45d0 100644
--- a/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/BindAuthenticator.java
+++ b/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/BindAuthenticator.java
@@ -26,7 +26,6 @@ import org.acegisecurity.userdetails.ldap.LdapUserDetailsImpl;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
-import javax.naming.NamingException;
 import java.util.Iterator;
 
 
@@ -47,7 +46,7 @@ public class BindAuthenticator extends AbstractLdapAuthenticator {
 
     /**
      * Create an initialized instance to the {@link InitialDirContextFactory} provided.
-     * 
+     *
      * @param initialDirContextFactory
      */
     public BindAuthenticator(InitialDirContextFactory initialDirContextFactory) {
@@ -74,7 +73,8 @@ public class BindAuthenticator extends AbstractLdapAuthenticator {
         }
 
         if (user == null) {
-            throw new BadCredentialsException(messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
+            throw new BadCredentialsException(
+                    messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
         }
 
         return user;
diff --git a/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/PasswordComparisonAuthenticator.java b/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/PasswordComparisonAuthenticator.java
index 28403f2ee5..64985af557 100644
--- a/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/PasswordComparisonAuthenticator.java
+++ b/core/src/main/java/org/acegisecurity/providers/ldap/authenticator/PasswordComparisonAuthenticator.java
@@ -37,12 +37,17 @@ import java.util.Iterator;
 
 /**
  * An {@link org.acegisecurity.providers.ldap.LdapAuthenticator LdapAuthenticator} which compares the login
- * password with the value stored in the directory.

This can be achieved either by retrieving the password - * attribute for the user and comparing it locally, or by peforming an LDAP "compare" operation. If the password - * attribute (default "userPassword") is found in the retrieved attributes it will be compared locally. If not, the - * remote comparison will be attempted.

- *

If passwords are stored in digest form in the repository, then a suitable {@link PasswordEncoder} - * implementation must be supplied. By default, passwords are encoded using the {@link LdapShaPasswordEncoder}.

+ * password with the value stored in the directory. + * + *

+ * This can be achieved either by retrieving the password attribute for the user and comparing it locally, + * or by peforming an LDAP "compare" operation. If the password attribute (default "userPassword") is found in the + * retrieved attributes it will be compared locally. If not, the remote comparison will be attempted. + *

+ *

+ * If passwords are stored in digest form in the repository, then a suitable {@link PasswordEncoder} + * implementation must be supplied. By default, passwords are encoded using the {@link LdapShaPasswordEncoder}. + *

* * @author Luke Taylor * @version $Id$ @@ -77,8 +82,8 @@ public final class PasswordComparisonAuthenticator extends AbstractLdapAuthentic final String userDn = (String) dns.next(); if (ldapTemplate.nameExists(userDn)) { - LdapUserDetailsImpl.Essence userEssence = (LdapUserDetailsImpl.Essence) ldapTemplate.retrieveEntry(userDn, - getUserDetailsMapper(), getUserAttributes()); + LdapUserDetailsImpl.Essence userEssence = (LdapUserDetailsImpl.Essence) + ldapTemplate.retrieveEntry(userDn, getUserDetailsMapper(), getUserAttributes()); userEssence.setUsername(username); user = userEssence.createUserDetails(); } diff --git a/core/src/main/java/org/acegisecurity/providers/ldap/populator/DefaultLdapAuthoritiesPopulator.java b/core/src/main/java/org/acegisecurity/providers/ldap/populator/DefaultLdapAuthoritiesPopulator.java index a6ba2b5fed..f3a7da3bd5 100644 --- a/core/src/main/java/org/acegisecurity/providers/ldap/populator/DefaultLdapAuthoritiesPopulator.java +++ b/core/src/main/java/org/acegisecurity/providers/ldap/populator/DefaultLdapAuthoritiesPopulator.java @@ -39,27 +39,30 @@ import javax.naming.directory.SearchControls; /** - * The default strategy for obtaining user role information from the directory.

It obtains roles by - * performing a search for "groups" the user is a member of. - *

- *

A typical group search scenario would be where each group/role is specified using the groupOfNames + * The default strategy for obtaining user role information from the directory. + *

It obtains roles by performing a search for "groups" the user is a member of. + *

+ *

A typical group search scenario would be where each group/role is specified using the groupOfNames * (or groupOfUniqueNames) LDAP objectClass and the user's DN is listed in the member (or * uniqueMember) attribute to indicate that they should be assigned that role. The following LDIF sample has * the groups stored under the DN ou=groups,dc=acegisecurity,dc=org and a group called "developers" with * "ben" and "marissa" as members: - *

dn: ou=groups,dc=acegisecurity,dc=orgobjectClass: top
+ * 
+ * dn: ou=groups,dc=acegisecurity,dc=orgobjectClass: top
  * objectClass: organizationalUnitou: groupsdn: cn=developers,ou=groups,dc=acegisecurity,dc=org
  * objectClass: groupOfNamesobjectClass: topcn: developersdescription: Acegi Security Developers
  * member: uid=ben,ou=people,dc=acegisecurity,dc=orgmember: uid=marissa,ou=people,dc=acegisecurity,dc=orgou: developer
  * 
*

- *

The group search is performed within a DN specified by the groupSearchBase property, which should + *

The group search is performed within a DN specified by the groupSearchBase property, which should * be relative to the root DN of its InitialDirContextFactory. If the search base is null, group searching is * disabled. The filter used in the search is defined by the groupSearchFilter property, with the filter * argument {0} being the full DN of the user. You can also specify which attribute defines the role name by setting * the groupRoleAttribute property (the default is "cn").

- *

The configuration below shows how the group search might be performed with the above schema.

- * <bean id="ldapAuthoritiesPopulator" class="org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator">
+ * 

The configuration below shows how the group search might be performed with the above schema. + *

+ * <bean id="ldapAuthoritiesPopulator"
+ *         class="org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator">
  *   <constructor-arg><ref local="initialDirContextFactory"/></constructor-arg>
  *   <constructor-arg><value>ou=groups</value></constructor-arg>
  *   <property name="groupRoleAttribute"><value>ou</value></property>
@@ -68,8 +71,8 @@ import javax.naming.directory.SearchControls;
  *   <property name="rolePrefix"><value>ROLE_</value></property>
  *   <property name="convertToUpperCase"><value>true</value></property>
  * </bean>
- * 
A search for - * roles for user "uid=ben,ou=people,dc=acegisecurity,dc=org" would return the single granted authority + *
+ * A search for roles for user "uid=ben,ou=people,dc=acegisecurity,dc=org" would return the single granted authority * "ROLE_DEVELOPER".

* * @author Luke Taylor @@ -246,7 +249,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator /** * Set the {@link InitialDirContextFactory} - * + * * @param initialDirContextFactory supplies the contexts used to search for user roles. */ private void setInitialDirContextFactory(InitialDirContextFactory initialDirContextFactory) { @@ -259,7 +262,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator /** * Set the group search base (name to search under) - * + * * @param groupSearchBase if this is an empty string the search will be performed from the root DN of the context * factory. */ diff --git a/core/src/main/java/org/acegisecurity/providers/rcp/RemoteAuthenticationManager.java b/core/src/main/java/org/acegisecurity/providers/rcp/RemoteAuthenticationManager.java index 2886d8243f..c3a0282ba4 100644 --- a/core/src/main/java/org/acegisecurity/providers/rcp/RemoteAuthenticationManager.java +++ b/core/src/main/java/org/acegisecurity/providers/rcp/RemoteAuthenticationManager.java @@ -42,6 +42,6 @@ public interface RemoteAuthenticationManager { * * @throws RemoteAuthenticationException if the authentication failed. */ - public GrantedAuthority[] attemptAuthentication(String username, String password) + GrantedAuthority[] attemptAuthentication(String username, String password) throws RemoteAuthenticationException; } diff --git a/core/src/main/java/org/acegisecurity/providers/rememberme/RememberMeAuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/rememberme/RememberMeAuthenticationToken.java index 407a444049..2ab3e19f05 100644 --- a/core/src/main/java/org/acegisecurity/providers/rememberme/RememberMeAuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/rememberme/RememberMeAuthenticationToken.java @@ -31,7 +31,7 @@ import org.acegisecurity.providers.AbstractAuthenticationToken; public class RememberMeAuthenticationToken extends AbstractAuthenticationToken implements Serializable { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Object principal; private int keyHash; diff --git a/core/src/main/java/org/acegisecurity/providers/x509/X509AuthenticationToken.java b/core/src/main/java/org/acegisecurity/providers/x509/X509AuthenticationToken.java index 1f841fd283..b0f3c7d818 100644 --- a/core/src/main/java/org/acegisecurity/providers/x509/X509AuthenticationToken.java +++ b/core/src/main/java/org/acegisecurity/providers/x509/X509AuthenticationToken.java @@ -31,7 +31,7 @@ import java.security.cert.X509Certificate; public class X509AuthenticationToken extends AbstractAuthenticationToken { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Object principal; private X509Certificate credentials; diff --git a/core/src/main/java/org/acegisecurity/runas/RunAsUserToken.java b/core/src/main/java/org/acegisecurity/runas/RunAsUserToken.java index 6c91866ddb..8af6956890 100644 --- a/core/src/main/java/org/acegisecurity/runas/RunAsUserToken.java +++ b/core/src/main/java/org/acegisecurity/runas/RunAsUserToken.java @@ -29,7 +29,7 @@ import org.acegisecurity.providers.AbstractAuthenticationToken; public class RunAsUserToken extends AbstractAuthenticationToken { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Class originalAuthentication; private Object credentials; private Object principal; diff --git a/core/src/main/java/org/acegisecurity/securechannel/ChannelDecisionManager.java b/core/src/main/java/org/acegisecurity/securechannel/ChannelDecisionManager.java index 5d873425d2..0da00e0d8d 100644 --- a/core/src/main/java/org/acegisecurity/securechannel/ChannelDecisionManager.java +++ b/core/src/main/java/org/acegisecurity/securechannel/ChannelDecisionManager.java @@ -27,7 +27,7 @@ import javax.servlet.ServletException; /** * Decides whether a web channel provides sufficient security. - * + * * @author Ben Alex * @version $Id$ */ @@ -44,7 +44,7 @@ public interface ChannelDecisionManager { * @throws IOException DOCUMENT ME! * @throws ServletException DOCUMENT ME! */ - public void decide(FilterInvocation invocation, ConfigAttributeDefinition config) + void decide(FilterInvocation invocation, ConfigAttributeDefinition config) throws IOException, ServletException; /** @@ -57,5 +57,5 @@ public interface ChannelDecisionManager { * * @return true if this ChannelDecisionManager can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); } diff --git a/core/src/main/java/org/acegisecurity/securechannel/ChannelEntryPoint.java b/core/src/main/java/org/acegisecurity/securechannel/ChannelEntryPoint.java index ec98ad10dc..b3393f7b5f 100644 --- a/core/src/main/java/org/acegisecurity/securechannel/ChannelEntryPoint.java +++ b/core/src/main/java/org/acegisecurity/securechannel/ChannelEntryPoint.java @@ -24,7 +24,7 @@ import javax.servlet.ServletResponse; /** * May be used by a {@link ChannelProcessor} to launch a web channel. - * + * *

* ChannelProcessors can elect to launch a new web channel * directly, or they can delegate to another class. The @@ -49,6 +49,6 @@ public interface ChannelEntryPoint { * @throws IOException DOCUMENT ME! * @throws ServletException DOCUMENT ME! */ - public void commence(ServletRequest request, ServletResponse response) + void commence(ServletRequest request, ServletResponse response) throws IOException, ServletException; } diff --git a/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessingFilter.java b/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessingFilter.java index d239410cc3..20a15f8fb6 100644 --- a/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessingFilter.java @@ -77,8 +77,8 @@ public class ChannelProcessingFilter implements InitializingBean, Filter { if (iter == null) { if (logger.isWarnEnabled()) { - logger.warn( - "Could not validate configuration attributes as the FilterInvocationDefinitionSource did not return a ConfigAttributeDefinition Iterator"); + logger.warn("Could not validate configuration attributes as the FilterInvocationDefinitionSource did " + + "not return a ConfigAttributeDefinition Iterator"); } return; diff --git a/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessor.java b/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessor.java index c33957f4ab..6fbf4c9c61 100644 --- a/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessor.java +++ b/core/src/main/java/org/acegisecurity/securechannel/ChannelProcessor.java @@ -27,12 +27,12 @@ import javax.servlet.ServletException; /** * Decides whether a web channel meets a specific security condition. - * + * *

* ChannelProcessor implementations are iterated by the {@link * ChannelDecisionManagerImpl}. *

- * + * *

* If an implementation has an issue with the channel security, they should * take action themselves. The callers of the implementation do not take any @@ -55,7 +55,7 @@ public interface ChannelProcessor { * @throws IOException DOCUMENT ME! * @throws ServletException DOCUMENT ME! */ - public void decide(FilterInvocation invocation, ConfigAttributeDefinition config) + void decide(FilterInvocation invocation, ConfigAttributeDefinition config) throws IOException, ServletException; /** @@ -68,5 +68,5 @@ public interface ChannelProcessor { * * @return true if this ChannelProcessor can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); } diff --git a/core/src/main/java/org/acegisecurity/taglibs/authz/AccessControlListTag.java b/core/src/main/java/org/acegisecurity/taglibs/authz/AccessControlListTag.java index 3c780183af..db6238cf02 100644 --- a/core/src/main/java/org/acegisecurity/taglibs/authz/AccessControlListTag.java +++ b/core/src/main/java/org/acegisecurity/taglibs/authz/AccessControlListTag.java @@ -182,8 +182,8 @@ public class AccessControlListTag extends TagSupport { } else if (map.size() == 1) { sidRetrievalStrategy = (SidRetrievalStrategy) map.values().iterator().next(); } else { - throw new JspException( - "Found incorrect number of SidRetrievalStrategy instances in application context - you must have only have one!"); + throw new JspException("Found incorrect number of SidRetrievalStrategy instances in application " + + "context - you must have only have one!"); } map = applicationContext.getBeansOfType(ObjectIdentityRetrievalStrategy.class); @@ -193,8 +193,8 @@ public class AccessControlListTag extends TagSupport { } else if (map.size() == 1) { objectIdentityRetrievalStrategy = (ObjectIdentityRetrievalStrategy) map.values().iterator().next(); } else { - throw new JspException( - "Found incorrect number of ObjectIdentityRetrievalStrategy instances in application context - you must have only have one!"); + throw new JspException("Found incorrect number of ObjectIdentityRetrievalStrategy instances in " + + "application context - you must have only have one!"); } } } diff --git a/core/src/main/java/org/acegisecurity/taglibs/authz/AuthenticationTag.java b/core/src/main/java/org/acegisecurity/taglibs/authz/AuthenticationTag.java index 2125ba4c42..2a0f2a7830 100644 --- a/core/src/main/java/org/acegisecurity/taglibs/authz/AuthenticationTag.java +++ b/core/src/main/java/org/acegisecurity/taglibs/authz/AuthenticationTag.java @@ -48,7 +48,7 @@ import javax.servlet.jsp.tagext.TagSupport; public class AuthenticationTag extends TagSupport { //~ Static fields/initializers ===================================================================================== - private final static Set methodPrefixValidOptions = new HashSet(); + private static final Set methodPrefixValidOptions = new HashSet(); static { methodPrefixValidOptions.add("get"); diff --git a/core/src/main/java/org/acegisecurity/taglibs/authz/AuthorizeTag.java b/core/src/main/java/org/acegisecurity/taglibs/authz/AuthorizeTag.java index 23ca483e80..c3bd3656fe 100644 --- a/core/src/main/java/org/acegisecurity/taglibs/authz/AuthorizeTag.java +++ b/core/src/main/java/org/acegisecurity/taglibs/authz/AuthorizeTag.java @@ -148,8 +148,8 @@ public class AuthorizeTag extends TagSupport { for (int i = 0; i < authorities.length; i++) { String authority = authorities[i]; - // Remove the role's whitespace characters without depending on JDK 1.4+ - // Includes space, tab, new line, carriage return and form feed. + // Remove the role's whitespace characters without depending on JDK 1.4+ + // Includes space, tab, new line, carriage return and form feed. String role = authority.trim(); // trim, don't use spaces, as per SEC-378 role = StringUtils.replace(role, "\t", ""); role = StringUtils.replace(role, "\r", ""); @@ -168,10 +168,12 @@ public class AuthorizeTag extends TagSupport { * iterate over both collections, because the granted authorities might not implement {@link * Object#equals(Object)} and {@link Object#hashCode()} in the same way as {@link GrantedAuthorityImpl}, thereby * invalidating {@link Collection#retainAll(java.util.Collection)} results.

- *

CAVEAT: This method will not work if the granted authorities + *

+ * CAVEAT: This method will not work if the granted authorities * returns a null string as the return value of {@link - * org.acegisecurity.GrantedAuthority#getAuthority()}.

- *

Reported by rawdave, on Fri Feb 04, 2005 2:11 pm in the Acegi Security System for Spring forums.

+ * org.acegisecurity.GrantedAuthority#getAuthority()}. + *

+ *

Reported by rawdave, on Fri Feb 04, 2005 2:11 pm in the Acegi Security System for Spring forums.

* * @param granted The authorities granted by the authentication. May be any implementation of {@link * GrantedAuthority} that does not return null from {@link @@ -182,7 +184,7 @@ public class AuthorizeTag extends TagSupport { * @return A set containing only the common authorities between granted and required. * * @see authz:authorize ifNotGranted not behaving - * as expected + * as expected TODO: wrong article Url */ private Set retainAll(final Collection granted, final Set required) { Set grantedRoles = authoritiesToRoles(granted); diff --git a/core/src/main/java/org/acegisecurity/taglibs/velocity/Authz.java b/core/src/main/java/org/acegisecurity/taglibs/velocity/Authz.java index f9f05cb67d..7bf9da73d7 100644 --- a/core/src/main/java/org/acegisecurity/taglibs/velocity/Authz.java +++ b/core/src/main/java/org/acegisecurity/taglibs/velocity/Authz.java @@ -45,7 +45,7 @@ public interface Authz { * * @return granted (true|false) */ - public boolean allGranted(String roles); + boolean allGranted(String roles); /** * any the listed roles must be granted to return true, otherwise fasle; @@ -54,14 +54,14 @@ public interface Authz { * * @return granted (true|false) */ - public boolean anyGranted(String roles); + boolean anyGranted(String roles); /** * set Spring application context which contains acegi related bean * * @return DOCUMENT ME! */ - public ApplicationContext getAppCtx(); + ApplicationContext getAppCtx(); /** * return the principal's name, supports the various type of principals that can exist in the {@link @@ -69,7 +69,7 @@ public interface Authz { * * @return string representation of principal's name */ - public String getPrincipal(); + String getPrincipal(); /** * return true if the principal holds either permission specified for the provided domain object

Only @@ -82,7 +82,7 @@ public interface Authz { * * @return got acl permission (true|false) */ - public boolean hasPermission(Object domainObject, String permissions); + boolean hasPermission(Object domainObject, String permissions); /** * none the listed roles must be granted to return true, otherwise fasle; @@ -91,12 +91,12 @@ public interface Authz { * * @return granted (true|false) */ - public boolean noneGranted(String roles); + boolean noneGranted(String roles); /** * get Spring application context which contains acegi related bean * * @param appCtx DOCUMENT ME! */ - public void setAppCtx(ApplicationContext appCtx); + void setAppCtx(ApplicationContext appCtx); } diff --git a/core/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java b/core/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java index ff72d117a6..d6c54c4b76 100644 --- a/core/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/ui/AbstractProcessingFilter.java @@ -135,8 +135,8 @@ public abstract class AbstractProcessingFilter implements Filter, InitializingBe private String filterProcessesUrl = getDefaultFilterProcessesUrl(); /** - * If true, will always redirect to the value of {@link #getDefaultTargetUrl} upon successful authentication, - * irrespective of the page that caused the authentication request (defaults to false). + * If true, will always redirect to the value of {@link #getDefaultTargetUrl} upon successful + * authentication, irrespective of the page that caused the authentication request (defaults to false). */ private boolean alwaysUseDefaultTargetUrl = false; @@ -429,8 +429,8 @@ public abstract class AbstractProcessingFilter implements Filter, InitializingBe sendRedirect(request, response, failureUrl); } - public AuthenticationDetailsSource getAuthenticationDetailsSource() { - // Required due to SEC-310 - return authenticationDetailsSource; - } + public AuthenticationDetailsSource getAuthenticationDetailsSource() { + // Required due to SEC-310 + return authenticationDetailsSource; + } } diff --git a/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandler.java b/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandler.java index 3debb6262a..70d0045383 100644 --- a/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandler.java +++ b/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandler.java @@ -44,6 +44,6 @@ public interface AccessDeniedHandler { * @throws IOException in the event of an IOException * @throws ServletException in the event of a ServletException */ - public void handle(ServletRequest request, ServletResponse response, AccessDeniedException accessDeniedException) + void handle(ServletRequest request, ServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException; } diff --git a/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandlerImpl.java b/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandlerImpl.java index 8b35bb1d50..f2baf0752f 100644 --- a/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandlerImpl.java +++ b/core/src/main/java/org/acegisecurity/ui/AccessDeniedHandlerImpl.java @@ -45,7 +45,7 @@ public class AccessDeniedHandlerImpl implements AccessDeniedHandler { //~ Static fields/initializers ===================================================================================== public static final String ACEGI_SECURITY_ACCESS_DENIED_EXCEPTION_KEY = "ACEGI_SECURITY_403_EXCEPTION"; - protected final static Log logger = LogFactory.getLog(AccessDeniedHandlerImpl.class); + protected static final Log logger = LogFactory.getLog(AccessDeniedHandlerImpl.class); //~ Instance fields ================================================================================================ @@ -62,7 +62,7 @@ public class AccessDeniedHandlerImpl implements AccessDeniedHandler { // Perform RequestDispatcher "forward" RequestDispatcher rd = request.getRequestDispatcher(errorPage); - rd.forward(request, response); + rd.forward(request, response); } if (!response.isCommitted()) { diff --git a/core/src/main/java/org/acegisecurity/ui/AuthenticationDetailsSource.java b/core/src/main/java/org/acegisecurity/ui/AuthenticationDetailsSource.java index efede62867..25edbbf77c 100644 --- a/core/src/main/java/org/acegisecurity/ui/AuthenticationDetailsSource.java +++ b/core/src/main/java/org/acegisecurity/ui/AuthenticationDetailsSource.java @@ -35,5 +35,5 @@ public interface AuthenticationDetailsSource { * * @return a fully-configured authentication details instance */ - public Object buildDetails(HttpServletRequest request); + Object buildDetails(HttpServletRequest request); } diff --git a/core/src/main/java/org/acegisecurity/ui/AuthenticationEntryPoint.java b/core/src/main/java/org/acegisecurity/ui/AuthenticationEntryPoint.java index 52fceaef9c..f68f8bf607 100644 --- a/core/src/main/java/org/acegisecurity/ui/AuthenticationEntryPoint.java +++ b/core/src/main/java/org/acegisecurity/ui/AuthenticationEntryPoint.java @@ -49,6 +49,6 @@ public interface AuthenticationEntryPoint { * @throws IOException DOCUMENT ME! * @throws ServletException DOCUMENT ME! */ - public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) + void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException; } diff --git a/core/src/main/java/org/acegisecurity/ui/logout/LogoutHandler.java b/core/src/main/java/org/acegisecurity/ui/logout/LogoutHandler.java index 05dadf6c2d..8bd51e5324 100644 --- a/core/src/main/java/org/acegisecurity/ui/logout/LogoutHandler.java +++ b/core/src/main/java/org/acegisecurity/ui/logout/LogoutHandler.java @@ -23,10 +23,10 @@ import javax.servlet.http.HttpServletResponse; /** * Indicates a class that is able to participate in logout handling. - * + * *

* Called by {@link LogoutFilter}. - * + * * @author Ben Alex * @version $Id$ */ @@ -40,5 +40,5 @@ public interface LogoutHandler { * @param response the HTTP resonse * @param authentication the current principal details */ - public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); + void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); } diff --git a/core/src/main/java/org/acegisecurity/ui/logout/SecurityContextLogoutHandler.java b/core/src/main/java/org/acegisecurity/ui/logout/SecurityContextLogoutHandler.java index 4f70e7909c..2ae57494ea 100644 --- a/core/src/main/java/org/acegisecurity/ui/logout/SecurityContextLogoutHandler.java +++ b/core/src/main/java/org/acegisecurity/ui/logout/SecurityContextLogoutHandler.java @@ -37,8 +37,8 @@ import javax.servlet.http.HttpSession; public class SecurityContextLogoutHandler implements LogoutHandler { //~ Methods ======================================================================================================== - private boolean invalidateHttpSession = true; - + private boolean invalidateHttpSession = true; + /** * Requires the request to be passed in. * @@ -47,31 +47,31 @@ public class SecurityContextLogoutHandler implements LogoutHandler { * @param authentication not used (can be null) */ public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { - Assert.notNull(request, "HttpServletRequest required"); - if (invalidateHttpSession) { - HttpSession session = request.getSession(false); - if (session != null) { - session.invalidate(); - } - } - - SecurityContextHolder.clearContext(); + Assert.notNull(request, "HttpServletRequest required"); + if (invalidateHttpSession) { + HttpSession session = request.getSession(false); + if (session != null) { + session.invalidate(); + } + } + + SecurityContextHolder.clearContext(); + } + + public boolean isInvalidateHttpSession() { + return invalidateHttpSession; + } + + /** + * Causes the {@link HttpSession} to be invalidated when this + * {@link LogoutHandler} is invoked. Defaults to true. + * + * @param invalidateHttpSession true if you wish the session to be + * invalidated (default) or false if it should not be + */ + public void setInvalidateHttpSession(boolean invalidateHttpSession) { + this.invalidateHttpSession = invalidateHttpSession; } - public boolean isInvalidateHttpSession() { - return invalidateHttpSession; - } - /** - * Causes the {@link HttpSession} to be invalidated when this - * {@link LogoutHandler} is invoked. Defaults to true. - * - * @param invalidateHttpSession true if you wish the session to be - * invalidated (default) or false if it should not be - */ - public void setInvalidateHttpSession(boolean invalidateHttpSession) { - this.invalidateHttpSession = invalidateHttpSession; - } - - } diff --git a/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeProcessingFilter.java b/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeProcessingFilter.java index deb571894d..9616b1f0f3 100644 --- a/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeProcessingFilter.java @@ -123,9 +123,9 @@ public class RememberMeProcessingFilter implements Filter, InitializingBean, App } } catch (AuthenticationException authenticationException) { if (logger.isDebugEnabled()) { - logger.debug( - "SecurityContextHolder not populated with remember-me token, as AuthenticationManager rejected Authentication returned by RememberMeServices: '" - + rememberMeAuth + "'; invalidating remember-me token", authenticationException); + logger.debug("SecurityContextHolder not populated with remember-me token, as " + + "AuthenticationManager rejected Authentication returned by RememberMeServices: '" + + rememberMeAuth + "'; invalidating remember-me token", authenticationException); } rememberMeServices.loginFail(httpRequest, httpResponse); diff --git a/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeServices.java b/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeServices.java index 069cea6bf6..1c88788110 100644 --- a/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeServices.java +++ b/core/src/main/java/org/acegisecurity/ui/rememberme/RememberMeServices.java @@ -23,24 +23,24 @@ import javax.servlet.http.HttpServletResponse; /** * Implement by a class that is capable of providing a remember-me service. - * - *

+ * + *

* Acegi Security filters (namely {@link * org.acegisecurity.ui.AbstractProcessingFilter} and {@link * org.acegisecurity.ui.rememberme.RememberMeProcessingFilter} will call * the methods provided by an implementation of this interface. *

- * - *

+ * + *

* Implementations may implement any type of remember-me capability they wish. - * Rolling cookies (as per http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice) + * Rolling cookies (as per + * http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice) * can be used, as can simple implementations that don't require a persistent * store. Implementations also determine the validity period of a remember-me * cookie. This interface has been designed to accommodate any of these * remember-me models. *

- * + * *

* This interface does not define how remember-me services should offer a * "cancel all remember-me tokens" type capability, as this will be @@ -71,7 +71,7 @@ public interface RememberMeServices { * * @return a valid authentication object, or null if the request should not be authenticated */ - public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response); + Authentication autoLogin(HttpServletRequest request, HttpServletResponse response); /** * Called whenever an interactive authentication attempt was made, but the credentials supplied by the user @@ -81,7 +81,7 @@ public interface RememberMeServices { * @param request that contained an invalid authentication request * @param response to change, cancel or modify the remember-me token */ - public void loginFail(HttpServletRequest request, HttpServletResponse response); + void loginFail(HttpServletRequest request, HttpServletResponse response); /** * Called whenever an interactive authentication attempt is successful. An implementation may automatically @@ -93,6 +93,6 @@ public interface RememberMeServices { * @param response to change, cancel or modify the remember-me token * @param successfulAuthentication representing the successfully authenticated principal */ - public void loginSuccess(HttpServletRequest request, HttpServletResponse response, + void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication); } diff --git a/core/src/main/java/org/acegisecurity/ui/rememberme/TokenBasedRememberMeServices.java b/core/src/main/java/org/acegisecurity/ui/rememberme/TokenBasedRememberMeServices.java index 474d184a9e..4edabbad20 100644 --- a/core/src/main/java/org/acegisecurity/ui/rememberme/TokenBasedRememberMeServices.java +++ b/core/src/main/java/org/acegisecurity/ui/rememberme/TokenBasedRememberMeServices.java @@ -47,31 +47,43 @@ import javax.servlet.http.HttpServletResponse; /** - * Identifies previously remembered users by a Base-64 encoded cookie.

This implementation does not rely on an - * external database, so is attractive for simple applications. The cookie will be valid for a specific period from - * the date of the last {@link #loginSuccess(HttpServletRequest, HttpServletResponse, Authentication)}. As per the + * Identifies previously remembered users by a Base-64 encoded cookie. + * + *

+ * This implementation does not rely on an external database, so is attractive for simple applications. + * The cookie will be valid for a specific period from the date of the last + * {@link #loginSuccess(HttpServletRequest, HttpServletResponse, Authentication)}. As per the * interface contract, this method will only be called when the principal completes a successful interactive * authentication. As such the time period commences from the last authentication attempt where they furnished * credentials - not the time period they last logged in via remember-me. The implementation will only send a * remember-me token if the parameter defined by {@link #setParameter(String)} is present.

- *

An {@link org.acegisecurity.userdetails.UserDetailsService} is required by this implementation, so that it + * + *

An {@link org.acegisecurity.userdetails.UserDetailsService} is required by this implementation, so that it * can construct a valid Authentication from the returned {@link * org.acegisecurity.userdetails.UserDetails}. This is also necessary so that the user's password is available and can * be checked as part of the encoded cookie.

- *

The cookie encoded by this implementation adopts the following form:

- *

username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key) - * .

- *

As such, if the user changes their password any remember-me token will be invalidated. Equally, the system + * + *

+ * The cookie encoded by this implementation adopts the following form: + *

username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key)
+ *

+ *

+ * As such, if the user changes their password any remember-me token will be invalidated. Equally, the system * administrator may invalidate every remember-me token on issue by changing the key. This provides some reasonable * approaches to recovering from a remember-me token being left on a public machine (eg kiosk system, Internet cafe * etc). Most importantly, at no time is the user's password ever sent to the user agent, providing an important * security safeguard. Unfortunately the username is necessary in this implementation (as we do not want to rely on a * database for remember-me services) and as such high security applications should be aware of this occasionally - * undesired disclosure of a valid username.

- *

This is a basic remember-me implementation which is suitable for many applications. However, we recommend a - * database-based implementation if you require a more secure remember-me approach.

- *

By default the tokens will be valid for 14 days from the last successful authentication attempt. This can be - * changed using {@link #setTokenValiditySeconds(long)}.

+ * undesired disclosure of a valid username. + *

+ *

+ * This is a basic remember-me implementation which is suitable for many applications. However, we recommend a + * database-based implementation if you require a more secure remember-me approach. + *

+ *

+ * By default the tokens will be valid for 14 days from the last successful authentication attempt. This can be + * changed using {@link #setTokenValiditySeconds(long)}. + *

* * @author Ben Alex * @version $Id$ @@ -117,8 +129,9 @@ public class TokenBasedRememberMeServices implements RememberMeServices, Initial } // Decode token from Base64 - // format of token is: - // username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key) + // format of token is: + // username + ":" + expiryTime + ":" + + // Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key) String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes())); String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":"); @@ -240,13 +253,13 @@ public class TokenBasedRememberMeServices implements RememberMeServices, Initial } protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { - if (alwaysRemember) { - return true; - } - - return RequestUtils.getBooleanParameter(request, parameter, false); + if (alwaysRemember) { + return true; + } + + return RequestUtils.getBooleanParameter(request, parameter, false); } - + public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { // Exit if the principal hasn't asked to be remembered @@ -281,18 +294,20 @@ public class TokenBasedRememberMeServices implements RememberMeServices, Initial // construct token to put in cookie; format is: // username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key) - String signatureValue = new String(DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key)); + String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key); String tokenValue = username + ":" + expiryTime + ":" + signatureValue; String tokenValueBase64 = new String(Base64.encodeBase64(tokenValue.getBytes())); response.addCookie(makeValidCookie(expiryTime, tokenValueBase64, request)); if (logger.isDebugEnabled()) { - logger.debug("Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'"); + logger.debug("Added remember-me cookie for user '" + username + + "', expiry: '" + new Date(expiryTime) + "'"); } } public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { - cancelCookie(request, response, "Logout of user " + (authentication == null ? "Unknown" : authentication.getName())); + cancelCookie(request, response, "Logout of user " + + (authentication == null ? "Unknown" : authentication.getName())); } protected Cookie makeCancelCookie(HttpServletRequest request) { @@ -332,11 +347,11 @@ public class TokenBasedRememberMeServices implements RememberMeServices, Initial this.userDetailsService = userDetailsService; } - public boolean isAlwaysRemember() { - return alwaysRemember; - } + public boolean isAlwaysRemember() { + return alwaysRemember; + } - public void setAlwaysRemember(boolean alwaysRemember) { - this.alwaysRemember = alwaysRemember; - } + public void setAlwaysRemember(boolean alwaysRemember) { + this.alwaysRemember = alwaysRemember; + } } diff --git a/core/src/main/java/org/acegisecurity/ui/savedrequest/Enumerator.java b/core/src/main/java/org/acegisecurity/ui/savedrequest/Enumerator.java index 65ef181647..1eefd28acc 100644 --- a/core/src/main/java/org/acegisecurity/ui/savedrequest/Enumerator.java +++ b/core/src/main/java/org/acegisecurity/ui/savedrequest/Enumerator.java @@ -26,8 +26,8 @@ import java.util.NoSuchElementException; /** *

Adapter that wraps an Enumeration around a Java 2 collection Iterator.

- *

Constructors are provided to easily create such wrappers.

- *

This class is based on code in Apache Tomcat.

+ *

Constructors are provided to easily create such wrappers.

+ *

This class is based on code in Apache Tomcat.

* * @author Craig McClanahan * @author Andrey Grebnev @@ -36,7 +36,9 @@ import java.util.NoSuchElementException; public class Enumerator implements Enumeration { //~ Instance fields ================================================================================================ - /** The Iterator over which the Enumeration represented by this class actually operates. */ + /** + * The Iterator over which the Enumeration represented by this class actually operates. + */ private Iterator iterator = null; //~ Constructors =================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/ui/savedrequest/FastHttpDateFormat.java b/core/src/main/java/org/acegisecurity/ui/savedrequest/FastHttpDateFormat.java index 954420de27..a8e0c66bec 100644 --- a/core/src/main/java/org/acegisecurity/ui/savedrequest/FastHttpDateFormat.java +++ b/core/src/main/java/org/acegisecurity/ui/savedrequest/FastHttpDateFormat.java @@ -27,7 +27,7 @@ import java.util.TimeZone; /** *

Utility class to generate HTTP dates.

- *

This class is based on code in Apache Tomcat.

+ *

This class is based on code in Apache Tomcat.

* * @author Remy Maucherat * @author Andrey Grebnev @@ -47,7 +47,7 @@ public class FastHttpDateFormat { }; /** GMT timezone - all HTTP dates are on GMT */ - protected final static TimeZone gmtZone = TimeZone.getTimeZone("GMT"); + protected static final TimeZone gmtZone = TimeZone.getTimeZone("GMT"); static { format.setTimeZone(gmtZone); @@ -138,7 +138,7 @@ public class FastHttpDateFormat { * * @return Parsed date (or null if no formatter mached) */ - private static final Long internalParseDate(String value, DateFormat[] formats) { + private static Long internalParseDate(String value, DateFormat[] formats) { Date date = null; for (int i = 0; (date == null) && (i < formats.length); i++) { @@ -205,7 +205,7 @@ public class FastHttpDateFormat { * @param key Key to be updated * @param value New value */ - private static final void updateCache(HashMap cache, Object key, Object value) { + private static void updateCache(HashMap cache, Object key, Object value) { if (value == null) { return; } diff --git a/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java b/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java index 8dd714bc74..70e7250f97 100644 --- a/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java +++ b/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java @@ -115,9 +115,9 @@ public class SavedRequest implements java.io.Serializable { String[] paramValues = (String[]) o; this.addParameter(paramName, paramValues); } else { - if (logger.isWarnEnabled()) { - logger.warn("ServletRequest.getParameterMap() returned non-String array"); - } + if (logger.isWarnEnabled()) { + logger.warn("ServletRequest.getParameterMap() returned non-String array"); + } } } diff --git a/core/src/main/java/org/acegisecurity/ui/session/HttpSessionEventPublisher.java b/core/src/main/java/org/acegisecurity/ui/session/HttpSessionEventPublisher.java index 62dc01f69e..77310b8a7a 100644 --- a/core/src/main/java/org/acegisecurity/ui/session/HttpSessionEventPublisher.java +++ b/core/src/main/java/org/acegisecurity/ui/session/HttpSessionEventPublisher.java @@ -23,16 +23,19 @@ import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** - * Declared in web.xml as
<listener>
- * <listener-class>org.acegisecurity.ui.session.HttpSessionEventPublisher</listener-class></listener>
- * 
Publishes HttpSessionApplicationEvents to the Spring Root WebApplicationContext. Maps + * Declared in web.xml as + *
+ * <listener>
+ *     <listener-class>org.acegisecurity.ui.session.HttpSessionEventPublisher</listener-class>
+ * </listener>
+ * 
+ * + * Publishes HttpSessionApplicationEvents to the Spring Root WebApplicationContext. Maps * javax.servlet.http.HttpSessionListener.sessionCreated() to {@link HttpSessionCreatedEvent}. Maps * javax.servlet.http.HttpSessionListener.sessionDestroyed() to {@link HttpSessionDestroyedEvent}. * diff --git a/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserAuthorityChanger.java b/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserAuthorityChanger.java index a928fe6a47..2e3688dd3d 100644 --- a/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserAuthorityChanger.java +++ b/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserAuthorityChanger.java @@ -9,22 +9,22 @@ import org.acegisecurity.userdetails.UserDetails; /** * Allows subclasses to modify the {@link GrantedAuthority} list that will be assigned to the principal * when they assume the identity of a different principal. - * + * *

Configured against the {@link SwitchUserProcessingFilter}. - * + * * @author Ben Alex * @version $Id$ * */ public interface SwitchUserAuthorityChanger { - + /** * Allow subclasses to add or remove authorities that will be granted when in switch user mode. - * + * * @param targetUser the UserDetails representing the identity being switched to * @param currentAuthentication the current Authentication of the principal performing the switching * @param authoritiesToBeGranted all {@link GrantedAuthority} instances to be granted to the user, * excluding the special "switch user" authority that is used internally (guaranteed never null) */ - public void modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List authoritiesToBeGranted); + void modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, List authoritiesToBeGranted); } diff --git a/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserGrantedAuthority.java b/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserGrantedAuthority.java index fad832f92e..407d2f0e4e 100644 --- a/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserGrantedAuthority.java +++ b/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserGrantedAuthority.java @@ -31,7 +31,7 @@ import org.acegisecurity.GrantedAuthorityImpl; public class SwitchUserGrantedAuthority extends GrantedAuthorityImpl { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private Authentication source; //~ Constructors =================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserProcessingFilter.java b/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserProcessingFilter.java index 79538f5109..9a913fdb1e 100644 --- a/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/ui/switchuser/SwitchUserProcessingFilter.java @@ -280,9 +280,9 @@ public class SwitchUserProcessingFilter implements Filter, InitializingBean, App // Allow subclasses to change the authorities to be granted if (switchUserAuthorityChanger != null) { - switchUserAuthorityChanger.modifyGrantedAuthorities(targetUser, currentAuth, orig); + switchUserAuthorityChanger.modifyGrantedAuthorities(targetUser, currentAuth, orig); } - + // add the new switch user authority List newAuths = new ArrayList(orig); newAuths.add(switchAuthority); @@ -302,7 +302,7 @@ public class SwitchUserProcessingFilter implements Filter, InitializingBean, App public void destroy() {} /** - * + * * @see javax.servlet.Filter#doFilter */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) @@ -471,7 +471,7 @@ public class SwitchUserProcessingFilter implements Filter, InitializingBean, App * @param switchUserAuthorityChanger to use to fine-tune the authorities granted to subclasses (may be null if * SwitchUserProcessingFilter shoudl not fine-tune the authorities) */ - public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger) { - this.switchUserAuthorityChanger = switchUserAuthorityChanger; - } + public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger) { + this.switchUserAuthorityChanger = switchUserAuthorityChanger; + } } diff --git a/core/src/main/java/org/acegisecurity/ui/webapp/SiteminderAuthenticationProcessingFilter.java b/core/src/main/java/org/acegisecurity/ui/webapp/SiteminderAuthenticationProcessingFilter.java index 2f3ce4573f..62c5d2f2ed 100644 --- a/core/src/main/java/org/acegisecurity/ui/webapp/SiteminderAuthenticationProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/ui/webapp/SiteminderAuthenticationProcessingFilter.java @@ -76,7 +76,7 @@ public class SiteminderAuthenticationProcessingFilter extends AuthenticationProc //~ Methods ======================================================================================================== /** - * + * * @see org.acegisecurity.ui.AbstractProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest) */ public Authentication attemptAuthentication(HttpServletRequest request) @@ -201,15 +201,15 @@ public class SiteminderAuthenticationProcessingFilter extends AuthenticationProc int pathParamIndex = uri.indexOf(';'); if (pathParamIndex > 0) { - // strip everything after the first semi-colon + // strip everything after the first semi-colon uri = uri.substring(0, pathParamIndex); } - //attempt authentication if j_secuity_check is present or if the getDefaultTargetUrl() - //is present and user is not already authenticated. + //attempt authentication if j_secuity_check is present or if the getDefaultTargetUrl() + //is present and user is not already authenticated. boolean bAuthenticated = false; - SecurityContext context = (SecurityContext) request.getSession() - .getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY); + SecurityContext context = (SecurityContext) + request.getSession().getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY); if (context != null) { Authentication auth = context.getAuthentication(); @@ -222,7 +222,7 @@ public class SiteminderAuthenticationProcessingFilter extends AuthenticationProc // if true is returned then authentication will be attempted. boolean bAttemptAuthentication = (uri.endsWith(request.getContextPath() + getFilterProcessesUrl())) - || ((getDefaultTargetUrl() != null) && uri.endsWith(getDefaultTargetUrl()) && !bAuthenticated); + || ((getDefaultTargetUrl() != null) && uri.endsWith(getDefaultTargetUrl()) && !bAuthenticated); if (logger.isDebugEnabled()) { logger.debug("Authentication attempted for the following URI ==> " + uri + " is " + bAttemptAuthentication); diff --git a/core/src/main/java/org/acegisecurity/ui/x509/X509ProcessingFilter.java b/core/src/main/java/org/acegisecurity/ui/x509/X509ProcessingFilter.java index fcd1272f84..65e131e4cc 100644 --- a/core/src/main/java/org/acegisecurity/ui/x509/X509ProcessingFilter.java +++ b/core/src/main/java/org/acegisecurity/ui/x509/X509ProcessingFilter.java @@ -43,9 +43,14 @@ import java.io.IOException; import java.security.cert.X509Certificate; -import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.Filter; +import javax.servlet.ServletRequest; +import javax.servlet.ServletException; +import javax.servlet.FilterChain; +import javax.servlet.ServletResponse; +import javax.servlet.FilterConfig; /** @@ -96,7 +101,7 @@ public class X509ProcessingFilter implements Filter, InitializingBean, Applicati * @param filterChain DOCUMENT ME! * * @throws IOException DOCUMENT ME! - * @throws ServletException DOCUMENT ME! + * @throws javax.servlet.ServletException DOCUMENT ME! */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { diff --git a/core/src/main/java/org/acegisecurity/userdetails/User.java b/core/src/main/java/org/acegisecurity/userdetails/User.java index cac05e287b..5b8bb92d7f 100644 --- a/core/src/main/java/org/acegisecurity/userdetails/User.java +++ b/core/src/main/java/org/acegisecurity/userdetails/User.java @@ -31,7 +31,7 @@ import org.springframework.util.Assert; public class User implements UserDetails { //~ Instance fields ================================================================================================ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private String password; private String username; private GrantedAuthority[] authorities; @@ -42,8 +42,9 @@ public class User implements UserDetails { //~ Constructors =================================================================================================== -/** - * Construct the User with the details required by {@link org.acegisecurity.providers.dao.DaoAuthenticationProvider}. + /** + * Construct the User with the details required by + * {@link org.acegisecurity.providers.dao.DaoAuthenticationProvider}. * * @param username the username presented to the * DaoAuthenticationProvider @@ -66,8 +67,9 @@ public class User implements UserDetails { this(username, password, enabled, true, true, authorities); } -/** - * Construct the User with the details required by {@link org.acegisecurity.providers.dao.DaoAuthenticationProvider}. + /** + * Construct the User with the details required by + * {@link org.acegisecurity.providers.dao.DaoAuthenticationProvider}. * * @param username the username presented to the * DaoAuthenticationProvider @@ -95,8 +97,9 @@ public class User implements UserDetails { this(username, password, enabled, accountNonExpired, credentialsNonExpired, true, authorities); } -/** - * Construct the User with the details required by {@link org.acegisecurity.providers.dao.DaoAuthenticationProvider}. + /** + * Construct the User with the details required by + * {@link org.acegisecurity.providers.dao.DaoAuthenticationProvider}. * * @param username the username presented to the * DaoAuthenticationProvider @@ -156,9 +159,10 @@ public class User implements UserDetails { // We rely on constructor to guarantee non-null username and password return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername()) - && (this.isAccountNonExpired() == user.isAccountNonExpired()) - && (this.isAccountNonLocked() == user.isAccountNonLocked()) - && (this.isCredentialsNonExpired() == user.isCredentialsNonExpired()) && (this.isEnabled() == user.isEnabled())); + && (this.isAccountNonExpired() == user.isAccountNonExpired()) + && (this.isAccountNonLocked() == user.isAccountNonLocked()) + && (this.isCredentialsNonExpired() == user.isCredentialsNonExpired()) + && (this.isEnabled() == user.isEnabled())); } public GrantedAuthority[] getAuthorities() { diff --git a/core/src/main/java/org/acegisecurity/userdetails/UserDetails.java b/core/src/main/java/org/acegisecurity/userdetails/UserDetails.java index c1e19adb50..c88cad0f45 100644 --- a/core/src/main/java/org/acegisecurity/userdetails/UserDetails.java +++ b/core/src/main/java/org/acegisecurity/userdetails/UserDetails.java @@ -23,22 +23,22 @@ import java.io.Serializable; /** * Provides core user information. - * - *

+ * + *

* Implementations are not used directly by Acegi Security for security * purposes. They simply store user information which is later encapsulated * into {@link Authentication} objects. This allows non-security related user * information (such as email addresses, telephone numbers etc) to be stored * in a convenient location. *

- * - *

+ * + *

* Concrete implementations must take particular care to ensure the non-null * contract detailed for each method is enforced. See * {@link org.acegisecurity.userdetails.User} for a * reference implementation (which you might like to extend). *

- * + * *

* Concrete implementations should be immutable (value object semantics, * like a String). This is because the UserDetails will be @@ -56,21 +56,21 @@ public interface UserDetails extends Serializable { * * @return the authorities (never null) */ - public GrantedAuthority[] getAuthorities(); + GrantedAuthority[] getAuthorities(); /** * Returns the password used to authenticate the user. Cannot return null. * * @return the password (never null) */ - public String getPassword(); + String getPassword(); /** * Returns the username used to authenticate the user. Cannot return null. * * @return the username (never null) */ - public String getUsername(); + String getUsername(); /** * Indicates whether the user's account has expired. An expired account cannot be authenticated. @@ -78,14 +78,14 @@ public interface UserDetails extends Serializable { * @return true if the user's account is valid (ie non-expired), false if no longer valid * (ie expired) */ - public boolean isAccountNonExpired(); + boolean isAccountNonExpired(); /** * Indicates whether the user is locked or unlocked. A locked user cannot be authenticated. * * @return true if the user is not locked, false otherwise */ - public boolean isAccountNonLocked(); + boolean isAccountNonLocked(); /** * Indicates whether the user's credentials (password) has expired. Expired credentials prevent @@ -94,12 +94,12 @@ public interface UserDetails extends Serializable { * @return true if the user's credentials are valid (ie non-expired), false if no longer * valid (ie expired) */ - public boolean isCredentialsNonExpired(); + boolean isCredentialsNonExpired(); /** * Indicates whether the user is enabled or disabled. A disabled user cannot be authenticated. * * @return true if the user is enabled, false otherwise */ - public boolean isEnabled(); + boolean isEnabled(); } diff --git a/core/src/main/java/org/acegisecurity/userdetails/UserDetailsService.java b/core/src/main/java/org/acegisecurity/userdetails/UserDetailsService.java index 36a23d6ed4..84c7156f1a 100644 --- a/core/src/main/java/org/acegisecurity/userdetails/UserDetailsService.java +++ b/core/src/main/java/org/acegisecurity/userdetails/UserDetailsService.java @@ -23,7 +23,7 @@ import org.springframework.dao.DataAccessException; /** * Defines an interface for implementations that wish to provide data access * services to the {@link DaoAuthenticationProvider}. - * + * *

* The interface requires only one read-only method, which simplifies support * of new data access strategies. @@ -48,6 +48,6 @@ public interface UserDetailsService { * @throws UsernameNotFoundException if the user could not be found or the user has no GrantedAuthority * @throws DataAccessException if user could not be found for a repository-specific reason */ - public UserDetails loadUserByUsername(String username) + UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException; } diff --git a/core/src/main/java/org/acegisecurity/userdetails/jdbc/JdbcDaoImpl.java b/core/src/main/java/org/acegisecurity/userdetails/jdbc/JdbcDaoImpl.java index 36b51e595e..78fd55dc85 100644 --- a/core/src/main/java/org/acegisecurity/userdetails/jdbc/JdbcDaoImpl.java +++ b/core/src/main/java/org/acegisecurity/userdetails/jdbc/JdbcDaoImpl.java @@ -58,8 +58,10 @@ import javax.sql.DataSource; public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { //~ Static fields/initializers ===================================================================================== - public static final String DEF_USERS_BY_USERNAME_QUERY = "SELECT username,password,enabled FROM users WHERE username = ?"; - public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "SELECT username,authority FROM authorities WHERE username = ?"; + public static final String DEF_USERS_BY_USERNAME_QUERY = + "SELECT username,password,enabled FROM users WHERE username = ?"; + public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = + "SELECT username,authority FROM authorities WHERE username = ?"; //~ Instance fields ================================================================================================ diff --git a/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsImpl.java b/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsImpl.java index e1a69b61e4..1c0e6d5c4d 100644 --- a/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsImpl.java +++ b/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsImpl.java @@ -41,7 +41,7 @@ import javax.naming.ldap.Control; public class LdapUserDetailsImpl implements LdapUserDetails { //~ Static fields/initializers ===================================================================================== - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private static final GrantedAuthority[] NO_AUTHORITIES = new GrantedAuthority[0]; private static final Control[] NO_CONTROLS = new Control[0]; @@ -110,8 +110,8 @@ public class LdapUserDetailsImpl implements LdapUserDetails { * Variation of essence pattern. Used to create mutable intermediate object */ public static class Essence { - LdapUserDetailsImpl instance = createTarget(); - List mutableAuthorities = new ArrayList(); + private LdapUserDetailsImpl instance = createTarget(); + private List mutableAuthorities = new ArrayList(); public Essence() {} diff --git a/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsMapper.java b/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsMapper.java index 811f790747..05952f3ffb 100644 --- a/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsMapper.java +++ b/core/src/main/java/org/acegisecurity/userdetails/ldap/LdapUserDetailsMapper.java @@ -65,7 +65,7 @@ public class LdapUserDetailsMapper implements LdapEntryMapper { for (int i = 0; (roleAttributes != null) && (i < roleAttributes.length); i++) { Attribute roleAttribute = attributes.get(roleAttributes[i]); - if(roleAttribute == null) { + if (roleAttribute == null) { logger.debug("Couldn't read role attribute '" + roleAttributes[i] + "' for user " + dn); continue; } @@ -75,10 +75,11 @@ public class LdapUserDetailsMapper implements LdapEntryMapper { while (attributeRoles.hasMore()) { GrantedAuthority authority = createAuthority(attributeRoles.next()); - if(authority != null) { + if (authority != null) { essence.addAuthority(authority); } else { - logger.debug("Failed to create an authority value from attribute with Id: " + roleAttribute.getID()); + logger.debug("Failed to create an authority value from attribute with Id: " + + roleAttribute.getID()); } } } diff --git a/core/src/main/java/org/acegisecurity/util/EncryptionUtils.java b/core/src/main/java/org/acegisecurity/util/EncryptionUtils.java index 4c5e0bd291..caf25f442a 100644 --- a/core/src/main/java/org/acegisecurity/util/EncryptionUtils.java +++ b/core/src/main/java/org/acegisecurity/util/EncryptionUtils.java @@ -29,136 +29,136 @@ import org.springframework.util.Assert; /** * A static utility class that can encrypt and decrypt text. - * + * *

This class is useful if you have simple needs and wish to use the DESede * encryption cipher. More sophisticated requirements will need to use the * Java crypto libraries directly. - * + * * @author Alan Stewart * @author Ben Alex * @version $Id$ */ -public class EncryptionUtils { +public final class EncryptionUtils { - /** - * This is a static class that should not be instantiated. - */ - private EncryptionUtils() {} + /** + * This is a static class that should not be instantiated. + */ + private EncryptionUtils() {} - /** - * Converts a String into a byte array using UTF-8, falling back to the - * platform's default character set if UTF-8 fails. - * - * @param input the input (required) - * @return a byte array representation of the input string - */ - public static byte[] stringToByteArray(String input) { - Assert.hasLength(input, "Input required"); - try { - return input.getBytes("UTF-8"); - } catch (UnsupportedEncodingException fallbackToDefault) { - return input.getBytes(); - } - } - - /** - * Converts a byte array into a String using UTF-8, falling back to the - * platform's default character set if UTF-8 fails. - * - * @param byteArray the byte array to convert (required) - * @return a string representation of the byte array - */ - public static String byteArrayToString(byte[] byteArray) { - Assert.notNull(byteArray, "ByteArray required"); - Assert.isTrue(byteArray.length > 0, "ByteArray cannot be empty"); - try { - return new String(byteArray, "UTF8"); - } catch (final UnsupportedEncodingException e) { - return new String(byteArray); - } - } - - private static byte[] cipher(String key, byte[] passedBytes, int cipherMode) throws EncryptionException { - try { - final KeySpec keySpec = new DESedeKeySpec(stringToByteArray(key)); - final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); - final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); - final SecretKey secretKey = keyFactory.generateSecret(keySpec); - cipher.init(cipherMode, secretKey); - return cipher.doFinal(passedBytes); - } catch (final Exception e) { - throw new EncryptionException(e.getMessage(), e); - } - } + /** + * Converts a String into a byte array using UTF-8, falling back to the + * platform's default character set if UTF-8 fails. + * + * @param input the input (required) + * @return a byte array representation of the input string + */ + public static byte[] stringToByteArray(String input) { + Assert.hasLength(input, "Input required"); + try { + return input.getBytes("UTF-8"); + } catch (UnsupportedEncodingException fallbackToDefault) { + return input.getBytes(); + } + } - /** - * Encrypts the inputString using the key. - * - * @param key at least 24 character long key (required) - * @param inputString the string to encrypt (required) - * @return the encrypted version of the inputString - * @throws EncryptionException in the event of an encryption failure - */ - public static String encrypt(String key, String inputString) throws EncryptionException { - isValidKey(key); - final byte[] cipherText = cipher(key, stringToByteArray(inputString), Cipher.ENCRYPT_MODE); - return byteArrayToString(Base64.encodeBase64(cipherText)); - } + /** + * Converts a byte array into a String using UTF-8, falling back to the + * platform's default character set if UTF-8 fails. + * + * @param byteArray the byte array to convert (required) + * @return a string representation of the byte array + */ + public static String byteArrayToString(byte[] byteArray) { + Assert.notNull(byteArray, "ByteArray required"); + Assert.isTrue(byteArray.length > 0, "ByteArray cannot be empty"); + try { + return new String(byteArray, "UTF8"); + } catch (final UnsupportedEncodingException e) { + return new String(byteArray); + } + } - /** - * Encrypts the inputBytes using the key. - * - * @param key at least 24 character long key (required) - * @param inputBytes the bytes to encrypt (required) - * @return the encrypted version of the inputBytes - * @throws EncryptionException in the event of an encryption failure - */ - public static byte[] encrypt(String key, byte[] inputBytes) throws EncryptionException { - isValidKey(key); - return Base64.encodeBase64(cipher(key, inputBytes, Cipher.ENCRYPT_MODE)); - } + private static byte[] cipher(String key, byte[] passedBytes, int cipherMode) throws EncryptionException { + try { + final KeySpec keySpec = new DESedeKeySpec(stringToByteArray(key)); + final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); + final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); + final SecretKey secretKey = keyFactory.generateSecret(keySpec); + cipher.init(cipherMode, secretKey); + return cipher.doFinal(passedBytes); + } catch (final Exception e) { + throw new EncryptionException(e.getMessage(), e); + } + } - /** - * Decrypts the inputString using the key. - * - * @param key the key used to originally encrypt the string (required) - * @param inputString the encrypted string (required) - * @return the decrypted version of inputString - * @throws EncryptionException in the event of an encryption failure - */ - public static String decrypt(String key, String inputString) throws EncryptionException { - Assert.hasText(key, "A key is required to attempt decryption"); - final byte[] cipherText = cipher(key, Base64.decodeBase64(stringToByteArray(inputString)), Cipher.DECRYPT_MODE); - return byteArrayToString(cipherText); - } + /** + * Encrypts the inputString using the key. + * + * @param key at least 24 character long key (required) + * @param inputString the string to encrypt (required) + * @return the encrypted version of the inputString + * @throws EncryptionException in the event of an encryption failure + */ + public static String encrypt(String key, String inputString) throws EncryptionException { + isValidKey(key); + final byte[] cipherText = cipher(key, stringToByteArray(inputString), Cipher.ENCRYPT_MODE); + return byteArrayToString(Base64.encodeBase64(cipherText)); + } - /** - * Decrypts the inputBytes using the key. - * - * @param key the key used to originally encrypt the string (required) - * @param inputBytes the encrypted bytes (required) - * @return the decrypted version of inputBytes - * @throws EncryptionException in the event of an encryption failure - */ - public static byte[] decrypt(String key, byte[] inputBytes) throws EncryptionException { - Assert.hasText(key, "A key is required to attempt decryption"); - return cipher(key, Base64.decodeBase64(inputBytes), Cipher.DECRYPT_MODE); - } - - private static void isValidKey(String key) { - Assert.hasText(key, "A key to perform the encryption is required"); - Assert.isTrue(key.length() >= 24, "Key must be at least 24 characters long"); - } + /** + * Encrypts the inputBytes using the key. + * + * @param key at least 24 character long key (required) + * @param inputBytes the bytes to encrypt (required) + * @return the encrypted version of the inputBytes + * @throws EncryptionException in the event of an encryption failure + */ + public static byte[] encrypt(String key, byte[] inputBytes) throws EncryptionException { + isValidKey(key); + return Base64.encodeBase64(cipher(key, inputBytes, Cipher.ENCRYPT_MODE)); + } - public static class EncryptionException extends AcegiSecurityException { - private static final long serialVersionUID = 1L; + /** + * Decrypts the inputString using the key. + * + * @param key the key used to originally encrypt the string (required) + * @param inputString the encrypted string (required) + * @return the decrypted version of inputString + * @throws EncryptionException in the event of an encryption failure + */ + public static String decrypt(String key, String inputString) throws EncryptionException { + Assert.hasText(key, "A key is required to attempt decryption"); + final byte[] cipherText = cipher(key, Base64.decodeBase64(stringToByteArray(inputString)), Cipher.DECRYPT_MODE); + return byteArrayToString(cipherText); + } - public EncryptionException(String message, Throwable t) { - super(message, t); - } + /** + * Decrypts the inputBytes using the key. + * + * @param key the key used to originally encrypt the string (required) + * @param inputBytes the encrypted bytes (required) + * @return the decrypted version of inputBytes + * @throws EncryptionException in the event of an encryption failure + */ + public static byte[] decrypt(String key, byte[] inputBytes) throws EncryptionException { + Assert.hasText(key, "A key is required to attempt decryption"); + return cipher(key, Base64.decodeBase64(inputBytes), Cipher.DECRYPT_MODE); + } - public EncryptionException(String message) { - super(message); - } - } + private static void isValidKey(String key) { + Assert.hasText(key, "A key to perform the encryption is required"); + Assert.isTrue(key.length() >= 24, "Key must be at least 24 characters long"); + } + + public static class EncryptionException extends AcegiSecurityException { + private static final long serialVersionUID = 1L; + + public EncryptionException(String message, Throwable t) { + super(message, t); + } + + public EncryptionException(String message) { + super(message); + } + } } diff --git a/core/src/main/java/org/acegisecurity/util/FieldUtils.java b/core/src/main/java/org/acegisecurity/util/FieldUtils.java index d549608dcf..839bd24b93 100644 --- a/core/src/main/java/org/acegisecurity/util/FieldUtils.java +++ b/core/src/main/java/org/acegisecurity/util/FieldUtils.java @@ -27,7 +27,12 @@ import java.lang.reflect.Field; * @author Ben Alex * @version $Id$ */ -public class FieldUtils { +public final class FieldUtils { + //~ Constructors =================================================================================================== + + private FieldUtils() { + } + //~ Methods ======================================================================================================== public static String getAccessorName(String fieldName, Class type) { diff --git a/core/src/main/java/org/acegisecurity/util/FilterChainProxy.java b/core/src/main/java/org/acegisecurity/util/FilterChainProxy.java index 0613baa703..e926e09bde 100644 --- a/core/src/main/java/org/acegisecurity/util/FilterChainProxy.java +++ b/core/src/main/java/org/acegisecurity/util/FilterChainProxy.java @@ -99,7 +99,8 @@ public class FilterChainProxy implements Filter, InitializingBean, ApplicationCo public void afterPropertiesSet() throws Exception { Assert.notNull(filterInvocationDefinitionSource, "filterInvocationDefinitionSource must be specified"); Assert.notNull(this.filterInvocationDefinitionSource.getConfigAttributeDefinitions(), - "FilterChainProxy requires the FilterInvocationDefinitionSource to return a non-null response to getConfigAttributeDefinitions()"); + "FilterChainProxy requires the FilterInvocationDefinitionSource to return a non-null response to " + + "getConfigAttributeDefinitions()"); } public void destroy() { diff --git a/core/src/main/java/org/acegisecurity/util/FilterInvocationUtils.java b/core/src/main/java/org/acegisecurity/util/FilterInvocationUtils.java index 8d63fb7c40..a38e4daea1 100644 --- a/core/src/main/java/org/acegisecurity/util/FilterInvocationUtils.java +++ b/core/src/main/java/org/acegisecurity/util/FilterInvocationUtils.java @@ -38,7 +38,12 @@ import javax.servlet.ServletResponse; * @author Ben Alex * @version $Id$ */ -public class FilterInvocationUtils { +public final class FilterInvocationUtils { + //~ Constructors =================================================================================================== + + private FilterInvocationUtils() { + } + //~ Methods ======================================================================================================== /** diff --git a/core/src/main/java/org/acegisecurity/util/FilterToBeanProxy.java b/core/src/main/java/org/acegisecurity/util/FilterToBeanProxy.java index 4ff3921860..00909fe58c 100644 --- a/core/src/main/java/org/acegisecurity/util/FilterToBeanProxy.java +++ b/core/src/main/java/org/acegisecurity/util/FilterToBeanProxy.java @@ -36,16 +36,16 @@ import javax.servlet.ServletResponse; /** *

Delegates Filter requests to a Spring-managed bean.

- * + * *

This class acts as a proxy on behalf of a * target Filter that is defined in the Spring bean context. It is necessary to specify which target * Filter should be proxied as a filter initialization parameter.

- * + * *

On filter initialisation, the class will use Spring's {@link * WebApplicationContextUtils#getWebApplicationContext(ServletContext sc)} method to obtain an * ApplicationContext instance. It will expect to find the target Filter in this * ApplicationContext.

- * + * *

To use this filter, it is necessary to specify one of the following filter initialization parameters: *

    *
  • targetClass indicates the class of the target Filter defined in the bean @@ -54,13 +54,13 @@ import javax.servlet.ServletResponse; *
  • targetBean indicates the bean name of the target class.
  • *
* If both initialization parameters are specified, targetBean takes priority.

- * + * *

An additional * initialization parameter, init, is also supported. If set to "lazy" the initialization * will take place on the first HTTP request, rather than at filter creation time. This makes it possible to use * FilterToBeanProxy with the Spring ContextLoaderServlet. Where possible you should not use * this initialization parameter, instead using ContextLoaderListener.

- * + * *

A final optional initialization parameter, lifecycle, determines whether the servlet container * or the IoC container manages the lifecycle of the proxied filter. When possible you should write your filters to be * managed via the IoC container interfaces such as {@link org.springframework.beans.factory.InitializingBean} and diff --git a/core/src/main/java/org/acegisecurity/util/InMemoryResource.java b/core/src/main/java/org/acegisecurity/util/InMemoryResource.java index 381dd1ab9e..7e202a285d 100644 --- a/core/src/main/java/org/acegisecurity/util/InMemoryResource.java +++ b/core/src/main/java/org/acegisecurity/util/InMemoryResource.java @@ -23,8 +23,8 @@ import java.io.InputStream; /** - * An in memory implementation of Spring's {@link org.springframework.core.io.Resource} interface.

Used by the - * "Acegifier" web application to create a bean factory from an XML string, rather than a file.

+ * An in memory implementation of Spring's {@link org.springframework.core.io.Resource} interface. + *

Used by the "Acegifier" web application to create a bean factory from an XML string, rather than a file.

* * @author Luke Taylor * @version $Id$ @@ -32,8 +32,8 @@ import java.io.InputStream; public class InMemoryResource extends AbstractResource { //~ Instance fields ================================================================================================ - ByteArrayInputStream in; - String description; + private ByteArrayInputStream in; + private String description; //~ Constructors =================================================================================================== diff --git a/core/src/main/java/org/acegisecurity/util/MethodInvocationUtils.java b/core/src/main/java/org/acegisecurity/util/MethodInvocationUtils.java index f43d76ec3f..5d1992e504 100644 --- a/core/src/main/java/org/acegisecurity/util/MethodInvocationUtils.java +++ b/core/src/main/java/org/acegisecurity/util/MethodInvocationUtils.java @@ -32,7 +32,12 @@ import java.util.List; * @author Ben Alex * @version $Id$ */ -public class MethodInvocationUtils { +public final class MethodInvocationUtils { + //~ Constructors =================================================================================================== + + private MethodInvocationUtils() { + } + //~ Methods ======================================================================================================== /** diff --git a/core/src/main/java/org/acegisecurity/util/PortMapper.java b/core/src/main/java/org/acegisecurity/util/PortMapper.java index 0951bcf03d..003bb329ed 100644 --- a/core/src/main/java/org/acegisecurity/util/PortMapper.java +++ b/core/src/main/java/org/acegisecurity/util/PortMapper.java @@ -33,7 +33,7 @@ public interface PortMapper { * * @return the HTTP port or null if unknown */ - public Integer lookupHttpPort(Integer httpsPort); + Integer lookupHttpPort(Integer httpsPort); /** * Locates the HTTPS port associated with the specified HTTP port.

Returns null if unknown.

@@ -42,5 +42,5 @@ public interface PortMapper { * * @return the HTTPS port or null if unknown */ - public Integer lookupHttpsPort(Integer httpPort); + Integer lookupHttpsPort(Integer httpPort); } diff --git a/core/src/main/java/org/acegisecurity/util/PortResolver.java b/core/src/main/java/org/acegisecurity/util/PortResolver.java index 875f1f0730..99d924411f 100644 --- a/core/src/main/java/org/acegisecurity/util/PortResolver.java +++ b/core/src/main/java/org/acegisecurity/util/PortResolver.java @@ -21,7 +21,7 @@ import javax.servlet.ServletRequest; /** * A PortResolver determines the port a web request was received * on. - * + * *

* This interface is necessary because * ServletRequest.getServerPort() may not return the correct port @@ -42,5 +42,5 @@ public interface PortResolver { * * @return the port the request was received on */ - public int getServerPort(ServletRequest request); + int getServerPort(ServletRequest request); } diff --git a/core/src/main/java/org/acegisecurity/util/StringSplitUtils.java b/core/src/main/java/org/acegisecurity/util/StringSplitUtils.java index a0735727ca..841cadeb57 100644 --- a/core/src/main/java/org/acegisecurity/util/StringSplitUtils.java +++ b/core/src/main/java/org/acegisecurity/util/StringSplitUtils.java @@ -28,7 +28,12 @@ import java.util.Map; * @author Ben Alex * @version $Id$ */ -public class StringSplitUtils { +public final class StringSplitUtils { + //~ Constructors =================================================================================================== + + private StringSplitUtils() { + } + //~ Methods ======================================================================================================== /** @@ -104,10 +109,9 @@ public class StringSplitUtils { return map; } - + public static String substringBeforeLast(String str, String separator) { - if (str == null || separator == null || str.length() == 0 || - separator.length() == 0) { + if (str == null || separator == null || str.length() == 0 || separator.length() == 0) { return str; } int pos = str.lastIndexOf(separator); @@ -116,7 +120,7 @@ public class StringSplitUtils { } return str.substring(0, pos); } - + public static String substringAfterLast(String str, String separator) { if (str == null || str.length() == 0) { return str; @@ -130,5 +134,5 @@ public class StringSplitUtils { } return str.substring(pos + separator.length()); } - + } diff --git a/core/src/main/java/org/acegisecurity/util/UrlUtils.java b/core/src/main/java/org/acegisecurity/util/UrlUtils.java index d910d5653b..ea5e33e024 100644 --- a/core/src/main/java/org/acegisecurity/util/UrlUtils.java +++ b/core/src/main/java/org/acegisecurity/util/UrlUtils.java @@ -29,7 +29,12 @@ import javax.servlet.http.HttpServletRequest; * @author Ben Alex * @version $Id$ */ -public class UrlUtils { +public final class UrlUtils { + //~ Constructors =================================================================================================== + + private UrlUtils() { + } + //~ Methods ======================================================================================================== /** @@ -50,6 +55,7 @@ public class UrlUtils { */ private static String buildFullRequestUrl(String scheme, String serverName, int serverPort, String contextPath, String requestUrl, String servletPath, String requestURI, String pathInfo, String queryString) { + boolean includePort = true; if ("http".equals(scheme.toLowerCase()) && (serverPort == 80)) { @@ -77,6 +83,7 @@ public class UrlUtils { */ private static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo, String queryString) { + String uri = servletPath; if (uri == null) { diff --git a/core/src/main/java/org/acegisecurity/vote/AccessDecisionVoter.java b/core/src/main/java/org/acegisecurity/vote/AccessDecisionVoter.java index 3e32e37d2c..b2f364aadd 100644 --- a/core/src/main/java/org/acegisecurity/vote/AccessDecisionVoter.java +++ b/core/src/main/java/org/acegisecurity/vote/AccessDecisionVoter.java @@ -22,7 +22,7 @@ import org.acegisecurity.ConfigAttributeDefinition; /** * Indicates a class is responsible for voting on authorization decisions. - * + * *

* The coordination of voting (ie polling AccessDecisionVoters, * tallying their responses, and making the final authorization decision) is @@ -35,9 +35,9 @@ import org.acegisecurity.ConfigAttributeDefinition; public interface AccessDecisionVoter { //~ Static fields/initializers ===================================================================================== - public static final int ACCESS_GRANTED = 1; - public static final int ACCESS_ABSTAIN = 0; - public static final int ACCESS_DENIED = -1; + int ACCESS_GRANTED = 1; + int ACCESS_ABSTAIN = 0; + int ACCESS_DENIED = -1; //~ Methods ======================================================================================================== @@ -52,7 +52,7 @@ public interface AccessDecisionVoter { * * @return true if this AccessDecisionVoter can support the passed configuration attribute */ - public boolean supports(ConfigAttribute attribute); + boolean supports(ConfigAttribute attribute); /** * Indicates whether the AccessDecisionVoter implementation is able to provide access control @@ -62,20 +62,22 @@ public interface AccessDecisionVoter { * * @return true if the implementation can process the indicated class */ - public boolean supports(Class clazz); + boolean supports(Class clazz); /** - * Indicates whether or not access is granted.

The decision must be affirmative - * (ACCESS_GRANTED), negative (ACCESS_DENIED) or the AccessDecisionVoter - * can abstain (ACCESS_ABSTAIN) from voting. Under no circumstances should implementing classes - * return any other value. If a weighting of results is desired, this should be handled in a custom {@link - * org.acegisecurity.AccessDecisionManager} instead.

- *

Unless an AccessDecisionVoter is specifically intended to vote on an access control + * Indicates whether or not access is granted. + *

The decision must be affirmative (ACCESS_GRANTED), negative (ACCESS_DENIED) + * or the AccessDecisionVoter can abstain (ACCESS_ABSTAIN) from voting. + * Under no circumstances should implementing classes return any other value. If a weighting of results is desired, + * this should be handled in a custom {@link org.acegisecurity.AccessDecisionManager} instead. + *

+ *

Unless an AccessDecisionVoter is specifically intended to vote on an access control * decision due to a passed method invocation or configuration attribute parameter, it must return * ACCESS_ABSTAIN. This prevents the coordinating AccessDecisionManager from counting * votes from those AccessDecisionVoters without a legitimate interest in the access control - * decision.

- *

Whilst the method invocation is passed as a parameter to maximise flexibility in making access + * decision. + *

+ *

Whilst the method invocation is passed as a parameter to maximise flexibility in making access * control decisions, implementing classes must never modify the behaviour of the method invocation (such as * calling MethodInvocation.proceed()).

* @@ -85,5 +87,5 @@ public interface AccessDecisionVoter { * * @return either {@link #ACCESS_GRANTED}, {@link #ACCESS_ABSTAIN} or {@link #ACCESS_DENIED} */ - public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config); + int vote(Authentication authentication, Object object, ConfigAttributeDefinition config); } diff --git a/core/src/main/java/org/acegisecurity/vote/AclEntryVoter.java b/core/src/main/java/org/acegisecurity/vote/AclEntryVoter.java index 89c178cb83..f12c3b456a 100644 --- a/core/src/main/java/org/acegisecurity/vote/AclEntryVoter.java +++ b/core/src/main/java/org/acegisecurity/vote/AclEntryVoter.java @@ -156,7 +156,7 @@ public class AclEntryVoter extends AbstractAclVoter { // Evaluate if we are required to use an inner domain object if (domainObject != null && internalMethod != null && (!"".equals(internalMethod))) { - try { + try { Class clazz = domainObject.getClass(); Method method = clazz.getMethod(internalMethod, new Class[] {}); domainObject = method.invoke(domainObject, new Object[] {}); @@ -196,7 +196,7 @@ public class AclEntryVoter extends AbstractAclVoter { return AccessDecisionVoter.ACCESS_ABSTAIN; } - + // Obtain the OID applicable to the domain object ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); diff --git a/core/src/main/java/org/acegisecurity/vote/LabelBasedAclVoter.java b/core/src/main/java/org/acegisecurity/vote/LabelBasedAclVoter.java index 5e62d4b3c7..3340c79888 100644 --- a/core/src/main/java/org/acegisecurity/vote/LabelBasedAclVoter.java +++ b/core/src/main/java/org/acegisecurity/vote/LabelBasedAclVoter.java @@ -18,8 +18,6 @@ import org.acegisecurity.Authentication; import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttributeDefinition; -import org.acegisecurity.vote.AbstractAclVoter; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; @@ -36,13 +34,16 @@ import java.util.Vector; /** *

This Acl voter will evaluate methods based on labels applied to incoming arguments. It will only check * methods that have been properly tagged in the MethodSecurityInterceptor with the value stored in - * attributeIndicatingLabeledOperation. If a method has been tagged, then it examines each argument, and if the - * argument implements {@link LabeledData}, then it will asses if the user's list of granted authorities matches.

- *

By default, if none of the arguments are labeled, then the access will be granted. This can be overridden by - * setting allowAccessIfNoAttributesAreLabeled to false in the Spring context file.

- *

In many situations, different values are linked together to define a common label, it is necessary to + * attributeIndicatingLabeledOperation. If a method has been tagged, then it examines each argument, and if the + * argument implements {@link LabeledData}, then it will asses if the user's list of granted authorities matches. + *

+ * + *

By default, if none of the arguments are labeled, then the access will be granted. This can be overridden by + * setting allowAccessIfNoAttributesAreLabeled to false in the Spring context file.

+ * + *

In many situations, different values are linked together to define a common label, it is necessary to * define a map in the application context that links user-assigned label access to domain object labels. This is done - * by setting up the labelMap in the application context.

+ * by setting up the labelMap in the application context.

* * @author Greg Turnquist * @version $Id$ @@ -50,18 +51,22 @@ import java.util.Vector; * @see org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor */ public class LabelBasedAclVoter extends AbstractAclVoter { + //~ Static fields/initializers ===================================================================================== + + private static final Log logger = LogFactory.getLog(LabelBasedAclVoter.class); + //~ Instance fields ================================================================================================ private HashMap labelMap = null; - Log logger = LogFactory.getLog(LabelBasedAclVoter.class); private String attributeIndicatingLabeledOperation = null; private boolean allowAccessIfNoAttributesAreLabeled = true; //~ Methods ======================================================================================================== /** - * Set whether or not to allow the user to run methods in which none of the incoming arguments are labeled.

Default - * value: true, users can run such methods.

+ * Set whether or not to allow the user to run methods in which none of the incoming arguments are labeled. + * + *

Default value: true, users can run such methods.

* * @param allowAccessIfNoAttributesAreLabeled boolean */ @@ -82,52 +87,55 @@ public class LabelBasedAclVoter extends AbstractAclVoter { /** * Set the map that correlate a user's assigned label against domain object values that are considered data - * labels.

+ * labels. An example application context configuration of a labelMap: * - * @param labelMap - HashMap Example application context configuration of a labelMap: - * *
-	 *  <bean id="accessDecisionManager" class="org.acegisecurity.vote.UnanimousBased">
- * <property name="allowIfAllAbstainDecisions"><value>false</value></property>
- * <property name="decisionVoters">
- * <list>
- * <bean class="org.acegisecurity.vote.RoleVoter"/>
- * <bean class="net.homelinux.scifi.LabelBasedAclVoter">
- * <property name="attributeIndicatingLabeledOperation"><value>LABELED_OPERATION</value></property>
- * <property name="labelMap">
- * <map>
- * <entry key="DATA_LABEL_BLUE">
- * <list>
- * <value>blue</value>
- * <value>indigo</value>
- * <value>purple</value>
- * </list>
- * </entry>
- * <entry key="LABEL_ORANGE">
- * <list>
- * <value>orange</value>
- * <value>sunshine</value>
- * <value>amber</value>
- * </list>
- * </entry>
- * <entry key="LABEL_ADMIN">
- * <list>
- * <value>blue</value>
- * <value>indigo</value>
- * <value>purple</value>
- * <value>orange</value>
- * <value>sunshine</value>
- * <value>amber</value>
- * </list>
- * </entry>
- * </map>
- * </property>
- * </bean>
- * </list>
- * </property>
- * </bean>
- *
- */ + * <bean id="accessDecisionManager" class="org.acegisecurity.vote.UnanimousBased"> + * <property name="allowIfAllAbstainDecisions"><value>false</value></property> + * <property name="decisionVoters"> + * <list> + * <bean class="org.acegisecurity.vote.RoleVoter"/> + * <bean class="org.acegisecurity.vote.LabelBasedAclVoter"> + * <property name="attributeIndicatingLabeledOperation"> + * <value>LABELED_OPERATION</value> + * </property> + * <property name="labelMap"> + * <map> + * <entry key="DATA_LABEL_BLUE"> + * <list> + * <value>blue</value> + * <value>indigo</value> + * <value>purple</value> + * </list> + * </entry> + * <entry key="LABEL_ORANGE"> + * <list> + * <value>orange</value> + * <value>sunshine</value> + * <value>amber</value> + * </list> + * </entry> + * <entry key="LABEL_ADMIN"> + * <list> + * <value>blue</value> + * <value>indigo</value> + * <value>purple</value> + * <value>orange</value> + * <value>sunshine</value> + * <value>amber</value> + * </list> + * </entry> + * </map> + * </property> + * </bean> + * </list> + * </property> + * </bean> + *
+ * + * @param labelMap a map structured as in the above example. + * + */ public void setLabelMap(HashMap labelMap) { this.labelMap = labelMap; } @@ -233,7 +241,8 @@ public class LabelBasedAclVoter extends AbstractAclVoter { logger.debug("We have a miss!"); misses++; } - } /* if arguments is an ILabel */} /* loop through all arguments */ + } + } Assert.isTrue((matches + misses) == labeledArguments, "The matches (" + matches + ") and misses (" + misses + " ) don't add up (" + labeledArguments + ")"); diff --git a/core/src/main/java/org/acegisecurity/vote/LabelParameterStrategy.java b/core/src/main/java/org/acegisecurity/vote/LabelParameterStrategy.java index fe1e8e2369..6f98565f02 100644 --- a/core/src/main/java/org/acegisecurity/vote/LabelParameterStrategy.java +++ b/core/src/main/java/org/acegisecurity/vote/LabelParameterStrategy.java @@ -37,7 +37,7 @@ public interface LabelParameterStrategy { * * @return string value of the label */ - public String getLabel(Method method, Object arg); + String getLabel(Method method, Object arg); /** * Evaluate if one particular argument is labeled. The context of the method is also provided should that @@ -48,5 +48,5 @@ public interface LabelParameterStrategy { * * @return boolean */ - public boolean isLabeled(Method method, Object arg); + boolean isLabeled(Method method, Object arg); } diff --git a/core/src/main/java/org/acegisecurity/vote/LabeledData.java b/core/src/main/java/org/acegisecurity/vote/LabeledData.java index 8499b8ebc5..6dd9d23869 100644 --- a/core/src/main/java/org/acegisecurity/vote/LabeledData.java +++ b/core/src/main/java/org/acegisecurity/vote/LabeledData.java @@ -19,7 +19,7 @@ package org.acegisecurity.vote; * This interface indicates data objects that carry a label. The purpose is to support * the {@link LabelBasedAclVoter}. When it votes, it evaluates all method arguments * tagged with this interface, and votes if they match the user's granted authorities list. - * + * * @author Greg Turnquist */ public interface LabeledData { @@ -31,5 +31,5 @@ public interface LabeledData { * * @return The label value of data object as a string. */ - public String getLabel(); + String getLabel(); } diff --git a/core/src/test/java/org/acegisecurity/ITargetObject.java b/core/src/test/java/org/acegisecurity/ITargetObject.java index e3fcff7c50..b2ce565416 100644 --- a/core/src/test/java/org/acegisecurity/ITargetObject.java +++ b/core/src/test/java/org/acegisecurity/ITargetObject.java @@ -24,13 +24,13 @@ package org.acegisecurity; public interface ITargetObject { //~ Methods ======================================================================================================== - public Integer computeHashCode(String input); + Integer computeHashCode(String input); - public int countLength(String input); + int countLength(String input); - public String makeLowerCase(String input); + String makeLowerCase(String input); - public String makeUpperCase(String input); + String makeUpperCase(String input); - public String publicMakeLowerCase(String input); + String publicMakeLowerCase(String input); } diff --git a/core/src/test/java/org/acegisecurity/acl/AclProviderManagerTests.java b/core/src/test/java/org/acegisecurity/acl/AclProviderManagerTests.java index 0521129900..987ba8a5f9 100644 --- a/core/src/test/java/org/acegisecurity/acl/AclProviderManagerTests.java +++ b/core/src/test/java/org/acegisecurity/acl/AclProviderManagerTests.java @@ -169,7 +169,10 @@ public class AclProviderManagerTests extends TestCase { new NamedEntityObjectIdentity("OBJECT", "100"), null, 2); private UsernamePasswordAuthenticationToken scott = new UsernamePasswordAuthenticationToken("scott", "not used", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_FOO"), new GrantedAuthorityImpl("ROLE_MANAGER")}); + new GrantedAuthority[] { + new GrantedAuthorityImpl("ROLE_FOO"), + new GrantedAuthorityImpl("ROLE_MANAGER") + }); private SimpleAclEntry entry100Scott = new SimpleAclEntry(scott.getPrincipal(), new NamedEntityObjectIdentity("OBJECT", "100"), null, 4); diff --git a/core/src/test/java/org/acegisecurity/ldap/LdapTestServer.java b/core/src/test/java/org/acegisecurity/ldap/LdapTestServer.java index 492d4b7698..4047859380 100644 --- a/core/src/test/java/org/acegisecurity/ldap/LdapTestServer.java +++ b/core/src/test/java/org/acegisecurity/ldap/LdapTestServer.java @@ -53,7 +53,7 @@ public class LdapTestServer { //~ Constructors =================================================================================================== -/** + /** * Starts up and configures ApacheDS. */ public LdapTestServer() { @@ -212,7 +212,7 @@ public class LdapTestServer { String apacheWorkDir = System.getProperty("apacheDSWorkDir"); - if(apacheWorkDir == null) { + if (apacheWorkDir == null) { apacheWorkDir = System.getProperty("java.io.tmpdir") + File.separator + "apacheds-work"; } @@ -244,7 +244,7 @@ public class LdapTestServer { } /** Recursively deletes a directory */ - private static boolean deleteDir(File dir) { + private boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i org.apache.maven.plugins maven-checkstyle-plugin + + acegi_checkstyle.xml + org.apache.maven.plugins diff --git a/samples/acegifier/src/main/java/acegifier/WebXmlConverter.java b/samples/acegifier/src/main/java/acegifier/WebXmlConverter.java index 747605d68d..b54cb360e5 100644 --- a/samples/acegifier/src/main/java/acegifier/WebXmlConverter.java +++ b/samples/acegifier/src/main/java/acegifier/WebXmlConverter.java @@ -53,9 +53,9 @@ public class WebXmlConverter { private Document newWebXml, acegiBeansXml; public WebXmlConverter() throws IOException, TransformerConfigurationException { - TransformerFactory tf = TransformerFactory.newInstance(); - Source source = createTransformerSource(WEB_TO_SPRING_XSL_FILE); - System.out.println("1"); + TransformerFactory tf = TransformerFactory.newInstance(); + Source source = createTransformerSource(WEB_TO_SPRING_XSL_FILE); + System.out.println("1"); acegiSecurityTransformer = tf.newTransformer(source); System.out.println("2"); newWebXmlTransformer = tf.newTransformer(createTransformerSource(NEW_WEB_XSLT_FILE)); @@ -109,14 +109,14 @@ public class WebXmlConverter { private void validateWebXml(Document document) throws DocumentException { Node authMethodNode = document.selectSingleNode("/web-app/login-config/auth-method"); - if(authMethodNode == null) + if (authMethodNode == null) throw new DocumentException("login-config and auth-method must be present"); String authMethod = authMethodNode.getStringValue().toUpperCase(); - if(!authMethod.equals("BASIC") && !authMethod.equals("FORM")) { + if (!authMethod.equals("BASIC") && !authMethod.equals("FORM")) { throw new DocumentException("unsupported auth-method: " + authMethod); } List roles = document.selectNodes("/web-app/security-role"); - if(roles.isEmpty()) { + if (roles.isEmpty()) { throw new DocumentException("Each role used must be defined in a security-role element"); } } diff --git a/samples/acegifier/src/test/java/acegifier/WebXmlConverterTests.java b/samples/acegifier/src/test/java/acegifier/WebXmlConverterTests.java index 80a037f7ff..dd643b4465 100644 --- a/samples/acegifier/src/test/java/acegifier/WebXmlConverterTests.java +++ b/samples/acegifier/src/test/java/acegifier/WebXmlConverterTests.java @@ -32,24 +32,24 @@ import org.dom4j.io.XMLWriter; */ public class WebXmlConverterTests extends TestCase { - private static final String XML_TRANSFORMER = "javax.xml.transform.TransformerFactory"; - + private static final String XML_TRANSFORMER = "javax.xml.transform.TransformerFactory"; + public void testFileConversion() throws Exception { - /* - - THIS TEST HAS BEEN DISABLED AS IT BREAKS THE BUILD (see SEC-181 for details) - - WebXmlConverter converter; - try { - converter = new WebXmlConverter(); - } catch (Exception e) { - // TODO: Something went wrong, set transforer manually and retry... - System.out.println("**** WARNING: NEEDING TO FALLBACK TO A MANUAL SYSTEM PROPERTY ****"); - System.setProperty(XML_TRANSFORMER, "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); - System.out.println(XML_TRANSFORMER + ": " + System.getProperty(XML_TRANSFORMER)); - converter = new WebXmlConverter(); - } - + /* + + THIS TEST HAS BEEN DISABLED AS IT BREAKS THE BUILD (see SEC-181 for details) + + WebXmlConverter converter; + try { + converter = new WebXmlConverter(); + } catch (Exception e) { + // TODO: Something went wrong, set transforer manually and retry... + System.out.println("**** WARNING: NEEDING TO FALLBACK TO A MANUAL SYSTEM PROPERTY ****"); + System.setProperty(XML_TRANSFORMER, "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); + System.out.println(XML_TRANSFORMER + ": " + System.getProperty(XML_TRANSFORMER)); + converter = new WebXmlConverter(); + } + Resource r = new ClassPathResource("test-web.xml"); converter.setInput(r.getInputStream()); converter.doConversion(); diff --git a/samples/attributes/src/main/java/sample/attributes/BankService.java b/samples/attributes/src/main/java/sample/attributes/BankService.java index 45ef0a9803..da05d364d9 100644 --- a/samples/attributes/src/main/java/sample/attributes/BankService.java +++ b/samples/attributes/src/main/java/sample/attributes/BankService.java @@ -24,29 +24,25 @@ package sample.attributes; * */ public interface BankService { - //~ Methods ================================================================ + //~ Methods ======================================================================================================== /** - * The SecurityConfig below will be merged with the interface-level - * SecurityConfig above by Commons Attributes. ie: this is equivalent to - * defining BankService=ROLE_TELLER,ROLE_PERMISSION_BALANACE in the bean - * context. + * The SecurityConfig below will be merged with the interface-level SecurityConfig above by Commons Attributes. + * ie: this is equivalent to defining BankService=ROLE_TELLER,ROLE_PERMISSION_BALANACE in the bean context. * * @return DOCUMENT ME! * * @@net.sf.acegisecurity.SecurityConfig("ROLE_PERMISSION_BALANCE") */ - public float balance(String accountNumber); + float balance(String accountNumber); /** - * The SecurityConfig below will be merged with the interface-level - * SecurityConfig above by Commons Attributes. ie: this is equivalent to - * defining BankService=ROLE_TELLER,ROLE_PERMISSION_LIST in the bean - * context. + * The SecurityConfig below will be merged with the interface-level SecurityConfig above by Commons Attributes. + * ie: this is equivalent to defining BankService=ROLE_TELLER,ROLE_PERMISSION_LIST in the bean context. * * @return DOCUMENT ME! * * @@net.sf.acegisecurity.SecurityConfig("ROLE_PERMISSION_LIST") */ - public String[] listAccounts(); + String[] listAccounts(); } diff --git a/samples/dms/src/main/java/sample/dms/AbstractElement.java b/samples/dms/src/main/java/sample/dms/AbstractElement.java index 614256134d..c45c0ec975 100755 --- a/samples/dms/src/main/java/sample/dms/AbstractElement.java +++ b/samples/dms/src/main/java/sample/dms/AbstractElement.java @@ -12,74 +12,74 @@ import org.springframework.util.Assert; * */ public abstract class AbstractElement { - /** The name of this token (ie filename or directory segment name */ - private String name; - - /** The parent of this token (ie directory, or null if referring to root) */ - private AbstractElement parent; - - /** The database identifier for this object (null if not persisted) */ - private Long id; - - /** - * Constructor to use to represent a root element. A root element has an id of -1. - */ - protected AbstractElement() { - this.name = "/"; - this.parent = null; - this.id = new Long(-1); - } - - /** - * Constructor to use to represent a non-root element. - * - * @param name name for this element (required, cannot be "/") - * @param parent for this element (required, cannot be null) - */ - protected AbstractElement(String name, AbstractElement parent) { - Assert.hasText(name, "Name required"); - Assert.notNull(parent, "Parent required"); - Assert.notNull(parent.getId(), "The parent must have been saved in order to create a child"); - this.name = name; - this.parent = parent; - } + /** The name of this token (ie filename or directory segment name */ + private String name; - public Long getId() { - return id; - } + /** The parent of this token (ie directory, or null if referring to root) */ + private AbstractElement parent; - /** - * @return the name of this token (never null, although will be "/" if root, otherwise it won't include separators) - */ - public String getName() { - return name; - } + /** The database identifier for this object (null if not persisted) */ + private Long id; - public AbstractElement getParent() { - return parent; - } - - /** - * @return the fully-qualified name of this element, including any parents - */ - public String getFullName() { - List strings = new ArrayList(); - AbstractElement currentElement = this; - while (currentElement != null) { - strings.add(0, currentElement.getName()); - currentElement = currentElement.getParent(); - } - - StringBuffer sb = new StringBuffer(); - String lastCharacter = null; - for (Iterator i = strings.iterator(); i.hasNext();) { - String token = (String) i.next(); - if (!"/".equals(lastCharacter) && lastCharacter != null) { - sb.append("/"); - } - sb.append(token); - lastCharacter = token.substring(token.length()-1); - } - return sb.toString(); - } + /** + * Constructor to use to represent a root element. A root element has an id of -1. + */ + protected AbstractElement() { + this.name = "/"; + this.parent = null; + this.id = new Long(-1); + } + + /** + * Constructor to use to represent a non-root element. + * + * @param name name for this element (required, cannot be "/") + * @param parent for this element (required, cannot be null) + */ + protected AbstractElement(String name, AbstractElement parent) { + Assert.hasText(name, "Name required"); + Assert.notNull(parent, "Parent required"); + Assert.notNull(parent.getId(), "The parent must have been saved in order to create a child"); + this.name = name; + this.parent = parent; + } + + public Long getId() { + return id; + } + + /** + * @return the name of this token (never null, although will be "/" if root, otherwise it won't include separators) + */ + public String getName() { + return name; + } + + public AbstractElement getParent() { + return parent; + } + + /** + * @return the fully-qualified name of this element, including any parents + */ + public String getFullName() { + List strings = new ArrayList(); + AbstractElement currentElement = this; + while (currentElement != null) { + strings.add(0, currentElement.getName()); + currentElement = currentElement.getParent(); + } + + StringBuffer sb = new StringBuffer(); + String lastCharacter = null; + for (Iterator i = strings.iterator(); i.hasNext();) { + String token = (String) i.next(); + if (!"/".equals(lastCharacter) && lastCharacter != null) { + sb.append("/"); + } + sb.append(token); + lastCharacter = token.substring(token.length()-1); + } + return sb.toString(); + } } diff --git a/samples/dms/src/main/java/sample/dms/DataSourcePopulator.java b/samples/dms/src/main/java/sample/dms/DataSourcePopulator.java index 9f14442c11..26e2552493 100755 --- a/samples/dms/src/main/java/sample/dms/DataSourcePopulator.java +++ b/samples/dms/src/main/java/sample/dms/DataSourcePopulator.java @@ -23,15 +23,15 @@ import org.springframework.util.Assert; * @version $Id$ */ public class DataSourcePopulator implements InitializingBean { - protected static final int LEVEL_NEGATE_READ = 0; - protected static final int LEVEL_GRANT_READ = 1; - protected static final int LEVEL_GRANT_WRITE = 2; - protected static final int LEVEL_GRANT_ADMIN = 3; - protected JdbcTemplate template; - protected DocumentDao documentDao; - protected TransactionTemplate tt; - - public DataSourcePopulator(DataSource dataSource, DocumentDao documentDao, PlatformTransactionManager platformTransactionManager) { + protected static final int LEVEL_NEGATE_READ = 0; + protected static final int LEVEL_GRANT_READ = 1; + protected static final int LEVEL_GRANT_WRITE = 2; + protected static final int LEVEL_GRANT_ADMIN = 3; + protected JdbcTemplate template; + protected DocumentDao documentDao; + protected TransactionTemplate tt; + + public DataSourcePopulator(DataSource dataSource, DocumentDao documentDao, PlatformTransactionManager platformTransactionManager) { Assert.notNull(dataSource, "DataSource required"); Assert.notNull(documentDao, "DocumentDao required"); Assert.notNull(platformTransactionManager, "PlatformTransactionManager required"); @@ -39,108 +39,108 @@ public class DataSourcePopulator implements InitializingBean { this.documentDao = documentDao; this.tt = new TransactionTemplate(platformTransactionManager); } - - public void afterPropertiesSet() throws Exception { - // ACL tables - template.execute("CREATE TABLE ACL_SID(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,PRINCIPAL BOOLEAN NOT NULL,SID VARCHAR_IGNORECASE(100) NOT NULL,CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));"); - template.execute("CREATE TABLE ACL_CLASS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,CLASS VARCHAR_IGNORECASE(100) NOT NULL,CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));"); - template.execute("CREATE TABLE ACL_OBJECT_IDENTITY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,OBJECT_ID_CLASS BIGINT NOT NULL,OBJECT_ID_IDENTITY BIGINT NOT NULL,PARENT_OBJECT BIGINT,OWNER_SID BIGINT,ENTRIES_INHERITING BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID),CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID),CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));"); - template.execute("CREATE TABLE ACL_ENTRY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL,MASK INTEGER NOT NULL,GRANTING BOOLEAN NOT NULL,AUDIT_SUCCESS BOOLEAN NOT NULL,AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER),CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID),CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));"); - // Normal authentication tables - template.execute("CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(50) NOT NULL,ENABLED BOOLEAN NOT NULL);"); - template.execute("CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));"); - template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);"); + public void afterPropertiesSet() throws Exception { + // ACL tables + template.execute("CREATE TABLE ACL_SID(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,PRINCIPAL BOOLEAN NOT NULL,SID VARCHAR_IGNORECASE(100) NOT NULL,CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));"); + template.execute("CREATE TABLE ACL_CLASS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,CLASS VARCHAR_IGNORECASE(100) NOT NULL,CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));"); + template.execute("CREATE TABLE ACL_OBJECT_IDENTITY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,OBJECT_ID_CLASS BIGINT NOT NULL,OBJECT_ID_IDENTITY BIGINT NOT NULL,PARENT_OBJECT BIGINT,OWNER_SID BIGINT,ENTRIES_INHERITING BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID),CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID),CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));"); + template.execute("CREATE TABLE ACL_ENTRY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL,MASK INTEGER NOT NULL,GRANTING BOOLEAN NOT NULL,AUDIT_SUCCESS BOOLEAN NOT NULL,AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER),CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID),CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));"); - // Document management system business tables - template.execute("CREATE TABLE DIRECTORY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY, DIRECTORY_NAME VARCHAR_IGNORECASE(50) NOT NULL, PARENT_DIRECTORY_ID BIGINT)"); - template.execute("CREATE TABLE FILE(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY, FILE_NAME VARCHAR_IGNORECASE(50) NOT NULL, CONTENT VARCHAR_IGNORECASE(1024), PARENT_DIRECTORY_ID BIGINT)"); - - // Populate the authentication and role tables - template.execute("INSERT INTO USERS VALUES('marissa','a564de63c2d0da68cf47586ee05984d7',TRUE);"); - template.execute("INSERT INTO USERS VALUES('dianne','65d15fe9156f9c4bbffd98085992a44e',TRUE);"); - template.execute("INSERT INTO USERS VALUES('scott','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); - template.execute("INSERT INTO USERS VALUES('peter','22b5c9accc6e1ba628cedc63a72d57f8',FALSE);"); - template.execute("INSERT INTO USERS VALUES('bill','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); - template.execute("INSERT INTO USERS VALUES('bob','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); - template.execute("INSERT INTO USERS VALUES('jane','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); - template.execute("INSERT INTO AUTHORITIES VALUES('marissa','ROLE_USER');"); - template.execute("INSERT INTO AUTHORITIES VALUES('marissa','ROLE_SUPERVISOR');"); - template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');"); - template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');"); - template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');"); - template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');"); - template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');"); - template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');"); - - // Now create an ACL entry for the root directory - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("marissa", "ignored", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_IGNORED")})); - tt.execute(new TransactionCallback() { - public Object doInTransaction(TransactionStatus arg0) { - addPermission(documentDao, Directory.ROOT_DIRECTORY, "ROLE_USER", LEVEL_GRANT_WRITE); - return null; - } - }); - - // Now go off and create some directories and files for our users - createSampleData("marissa", "koala"); - createSampleData("dianne", "emu"); - createSampleData("scott", "wombat"); - } + // Normal authentication tables + template.execute("CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(50) NOT NULL,ENABLED BOOLEAN NOT NULL);"); + template.execute("CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));"); + template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);"); + + // Document management system business tables + template.execute("CREATE TABLE DIRECTORY(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY, DIRECTORY_NAME VARCHAR_IGNORECASE(50) NOT NULL, PARENT_DIRECTORY_ID BIGINT)"); + template.execute("CREATE TABLE FILE(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY, FILE_NAME VARCHAR_IGNORECASE(50) NOT NULL, CONTENT VARCHAR_IGNORECASE(1024), PARENT_DIRECTORY_ID BIGINT)"); + + // Populate the authentication and role tables + template.execute("INSERT INTO USERS VALUES('marissa','a564de63c2d0da68cf47586ee05984d7',TRUE);"); + template.execute("INSERT INTO USERS VALUES('dianne','65d15fe9156f9c4bbffd98085992a44e',TRUE);"); + template.execute("INSERT INTO USERS VALUES('scott','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); + template.execute("INSERT INTO USERS VALUES('peter','22b5c9accc6e1ba628cedc63a72d57f8',FALSE);"); + template.execute("INSERT INTO USERS VALUES('bill','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); + template.execute("INSERT INTO USERS VALUES('bob','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); + template.execute("INSERT INTO USERS VALUES('jane','2b58af6dddbd072ed27ffc86725d7d3a',TRUE);"); + template.execute("INSERT INTO AUTHORITIES VALUES('marissa','ROLE_USER');"); + template.execute("INSERT INTO AUTHORITIES VALUES('marissa','ROLE_SUPERVISOR');"); + template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');"); + template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');"); + template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');"); + template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');"); + template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');"); + template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');"); + + // Now create an ACL entry for the root directory + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("marissa", "ignored", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_IGNORED")})); + tt.execute(new TransactionCallback() { + public Object doInTransaction(TransactionStatus arg0) { + addPermission(documentDao, Directory.ROOT_DIRECTORY, "ROLE_USER", LEVEL_GRANT_WRITE); + return null; + } + }); + + // Now go off and create some directories and files for our users + createSampleData("marissa", "koala"); + createSampleData("dianne", "emu"); + createSampleData("scott", "wombat"); + } /** * Creates a directory for the user, and a series of sub-directories. The root directory is the parent for the user directory. The sub-directories * are "confidential" and "shared". The ROLE_USER will be given read and write access to "shared". */ private void createSampleData(String username, String password) { - Assert.notNull(documentDao, "DocumentDao required"); - Assert.hasText(username, "Username required"); + Assert.notNull(documentDao, "DocumentDao required"); + Assert.hasText(username, "Username required"); - Authentication auth = new UsernamePasswordAuthenticationToken(username, password); - - try { - // Set the SecurityContextHolder ThreadLocal so any subclasses automatically know which user is operating - SecurityContextHolder.getContext().setAuthentication(auth); - - // Create the home directory first - Directory home = new Directory(username, Directory.ROOT_DIRECTORY); - documentDao.create(home); - addPermission(documentDao, home, username, LEVEL_GRANT_ADMIN); - addPermission(documentDao, home, "ROLE_USER", LEVEL_GRANT_READ); - createFiles(documentDao, home); - - // Now create the confidential directory - Directory confid = new Directory("confidential", home); - documentDao.create(confid); - addPermission(documentDao, confid, "ROLE_USER", LEVEL_NEGATE_READ); - createFiles(documentDao, confid); - - // Now create the shared directory - Directory shared = new Directory("shared", home); - documentDao.create(shared); - addPermission(documentDao, shared, "ROLE_USER", LEVEL_GRANT_READ); - addPermission(documentDao, shared, "ROLE_USER", LEVEL_GRANT_WRITE); - createFiles(documentDao, shared); - } finally { - // Clear the SecurityContextHolder ThreadLocal so future calls are guaranteed to be clean - SecurityContextHolder.clearContext(); - } + Authentication auth = new UsernamePasswordAuthenticationToken(username, password); + + try { + // Set the SecurityContextHolder ThreadLocal so any subclasses automatically know which user is operating + SecurityContextHolder.getContext().setAuthentication(auth); + + // Create the home directory first + Directory home = new Directory(username, Directory.ROOT_DIRECTORY); + documentDao.create(home); + addPermission(documentDao, home, username, LEVEL_GRANT_ADMIN); + addPermission(documentDao, home, "ROLE_USER", LEVEL_GRANT_READ); + createFiles(documentDao, home); + + // Now create the confidential directory + Directory confid = new Directory("confidential", home); + documentDao.create(confid); + addPermission(documentDao, confid, "ROLE_USER", LEVEL_NEGATE_READ); + createFiles(documentDao, confid); + + // Now create the shared directory + Directory shared = new Directory("shared", home); + documentDao.create(shared); + addPermission(documentDao, shared, "ROLE_USER", LEVEL_GRANT_READ); + addPermission(documentDao, shared, "ROLE_USER", LEVEL_GRANT_WRITE); + createFiles(documentDao, shared); + } finally { + // Clear the SecurityContextHolder ThreadLocal so future calls are guaranteed to be clean + SecurityContextHolder.clearContext(); + } } - + private void createFiles(DocumentDao documentDao, Directory parent) { - Assert.notNull(documentDao, "DocumentDao required"); - Assert.notNull(parent, "Parent required"); - int countBeforeInsert = documentDao.findElements(parent).length; - for (int i = 0; i < 10; i++) { - File file = new File("file_" + i + ".txt", parent); - documentDao.create(file); - } - Assert.isTrue(countBeforeInsert + 10 == documentDao.findElements(parent).length, "Failed to increase count by 10"); + Assert.notNull(documentDao, "DocumentDao required"); + Assert.notNull(parent, "Parent required"); + int countBeforeInsert = documentDao.findElements(parent).length; + for (int i = 0; i < 10; i++) { + File file = new File("file_" + i + ".txt", parent); + documentDao.create(file); + } + Assert.isTrue(countBeforeInsert + 10 == documentDao.findElements(parent).length, "Failed to increase count by 10"); } - + /** * Allows subclass to add permissions. - * + * * @param documentDao that will presumably offer methods to enable the operation to be completed * @param element to the subject of the new permissions * @param recipient to receive permission (if it starts with ROLE_ it is assumed to be a GrantedAuthority, else it is a username) diff --git a/samples/dms/src/main/java/sample/dms/Directory.java b/samples/dms/src/main/java/sample/dms/Directory.java index e82c412f61..98ce4e2b5d 100755 --- a/samples/dms/src/main/java/sample/dms/Directory.java +++ b/samples/dms/src/main/java/sample/dms/Directory.java @@ -1,24 +1,24 @@ package sample.dms; /** - * + * * @author Ben Alex * @version $Id$ * */ public class Directory extends AbstractElement { - public static final Directory ROOT_DIRECTORY = new Directory(); - - private Directory() { - super(); - } - - public Directory(String name, Directory parent) { - super(name, parent); - } + public static final Directory ROOT_DIRECTORY = new Directory(); - public String toString() { - return "Directory[fullName='" + getFullName() + "'; name='" + getName() + "'; id='" + getId() + "'; parent='" + getParent() + "']"; - } - + private Directory() { + super(); + } + + public Directory(String name, Directory parent) { + super(name, parent); + } + + public String toString() { + return "Directory[fullName='" + getFullName() + "'; name='" + getName() + "'; id='" + getId() + "'; parent='" + getParent() + "']"; + } + } diff --git a/samples/dms/src/main/java/sample/dms/DocumentDao.java b/samples/dms/src/main/java/sample/dms/DocumentDao.java index 03b1c00eb3..2d7fc82a91 100755 --- a/samples/dms/src/main/java/sample/dms/DocumentDao.java +++ b/samples/dms/src/main/java/sample/dms/DocumentDao.java @@ -2,38 +2,38 @@ package sample.dms; /** - * + * * @author Ben Alex * @version $Id$ * */ public interface DocumentDao { - /** - * Creates an entry in the database for the element. - * - * @param element an unsaved element (the "id" will be updated after method is invoked) - */ - public void create(AbstractElement element); - - /** - * Removes a file from the database for the specified element. - * - * @param file the file to remove (cannot be null) - */ - public void delete(File file); - - /** - * Modifies a file in the database. - * - * @param file the file to update (cannot be null) - */ - public void update(File file); - - /** - * Locates elements in the database which appear under the presented directory - * - * @param directory the directory (cannot be null - use {@link Directory#ROOT_DIRECTORY} for root) - * @return zero or more elements in the directory (an empty array may be returned - never null) - */ - public AbstractElement[] findElements(Directory directory); + /** + * Creates an entry in the database for the element. + * + * @param element an unsaved element (the "id" will be updated after method is invoked) + */ + public void create(AbstractElement element); + + /** + * Removes a file from the database for the specified element. + * + * @param file the file to remove (cannot be null) + */ + public void delete(File file); + + /** + * Modifies a file in the database. + * + * @param file the file to update (cannot be null) + */ + public void update(File file); + + /** + * Locates elements in the database which appear under the presented directory + * + * @param directory the directory (cannot be null - use {@link Directory#ROOT_DIRECTORY} for root) + * @return zero or more elements in the directory (an empty array may be returned - never null) + */ + public AbstractElement[] findElements(Directory directory); } diff --git a/samples/dms/src/main/java/sample/dms/DocumentDaoImpl.java b/samples/dms/src/main/java/sample/dms/DocumentDaoImpl.java index eece667263..00e4eb474c 100755 --- a/samples/dms/src/main/java/sample/dms/DocumentDaoImpl.java +++ b/samples/dms/src/main/java/sample/dms/DocumentDaoImpl.java @@ -12,104 +12,104 @@ import org.springframework.util.Assert; /** * Basic JDBC implementation of {@link DocumentDao}. - * + * * @author Ben Alex * @version $Id$ */ public class DocumentDaoImpl extends JdbcDaoSupport implements DocumentDao { - private static final String INSERT_INTO_DIRECTORY = "insert into directory(directory_name, parent_directory_id) values (?,?)"; - private static final String INSERT_INTO_FILE = "insert into file(file_name, content, parent_directory_id) values (?,?,?)"; - private static final String SELECT_FROM_DIRECTORY = "select id from directory where parent_directory_id = ?"; - private static final String SELECT_FROM_DIRECTORY_NULL = "select id from directory where parent_directory_id is null"; - private static final String SELECT_FROM_FILE = "select id, file_name, content, parent_directory_id from file where parent_directory_id = ?"; - private static final String SELECT_FROM_DIRECTORY_SINGLE = "select id, directory_name, parent_directory_id from directory where id = ?"; - private static final String DELETE_FROM_FILE = "delete from file where id = ?"; - private static final String UPDATE_FILE = "update file set content = ? where id = ?"; + private static final String INSERT_INTO_DIRECTORY = "insert into directory(directory_name, parent_directory_id) values (?,?)"; + private static final String INSERT_INTO_FILE = "insert into file(file_name, content, parent_directory_id) values (?,?,?)"; + private static final String SELECT_FROM_DIRECTORY = "select id from directory where parent_directory_id = ?"; + private static final String SELECT_FROM_DIRECTORY_NULL = "select id from directory where parent_directory_id is null"; + private static final String SELECT_FROM_FILE = "select id, file_name, content, parent_directory_id from file where parent_directory_id = ?"; + private static final String SELECT_FROM_DIRECTORY_SINGLE = "select id, directory_name, parent_directory_id from directory where id = ?"; + private static final String DELETE_FROM_FILE = "delete from file where id = ?"; + private static final String UPDATE_FILE = "update file set content = ? where id = ?"; private static final String SELECT_IDENTITY = "call identity()"; - private Long obtainPrimaryKey() { + private Long obtainPrimaryKey() { Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); return new Long(getJdbcTemplate().queryForLong(SELECT_IDENTITY)); - } - - public void create(AbstractElement element) { - Assert.notNull(element, "Element required"); - Assert.isNull(element.getId(), "Element has previously been saved"); - if (element instanceof Directory) { - Directory directory = (Directory) element; - Long parentId = directory.getParent() == null ? null : directory.getParent().getId(); - getJdbcTemplate().update(INSERT_INTO_DIRECTORY, new Object[] {directory.getName(), parentId}); - FieldUtils.setProtectedFieldValue("id", directory, obtainPrimaryKey()); - } else if (element instanceof File) { - File file = (File) element; - Long parentId = file.getParent() == null ? null : file.getParent().getId(); - getJdbcTemplate().update(INSERT_INTO_FILE, new Object[] {file.getName(), file.getContent(), parentId}); - FieldUtils.setProtectedFieldValue("id", file, obtainPrimaryKey()); - } else { - throw new IllegalArgumentException("Unsupported AbstractElement"); - } - } + } - public void delete(File file) { - Assert.notNull(file, "File required"); - Assert.notNull(file.getId(), "File ID required"); - getJdbcTemplate().update(DELETE_FROM_FILE, new Object[] {file.getId()}); - } + public void create(AbstractElement element) { + Assert.notNull(element, "Element required"); + Assert.isNull(element.getId(), "Element has previously been saved"); + if (element instanceof Directory) { + Directory directory = (Directory) element; + Long parentId = directory.getParent() == null ? null : directory.getParent().getId(); + getJdbcTemplate().update(INSERT_INTO_DIRECTORY, new Object[] {directory.getName(), parentId}); + FieldUtils.setProtectedFieldValue("id", directory, obtainPrimaryKey()); + } else if (element instanceof File) { + File file = (File) element; + Long parentId = file.getParent() == null ? null : file.getParent().getId(); + getJdbcTemplate().update(INSERT_INTO_FILE, new Object[] {file.getName(), file.getContent(), parentId}); + FieldUtils.setProtectedFieldValue("id", file, obtainPrimaryKey()); + } else { + throw new IllegalArgumentException("Unsupported AbstractElement"); + } + } - /** Executes recursive SQL as needed to build a full Directory hierarchy of objects */ - private Directory getDirectoryWithImmediateParentPopulated(final Long id) { - return (Directory) getJdbcTemplate().queryForObject(SELECT_FROM_DIRECTORY_SINGLE, new Object[] {id}, new RowMapper() { - public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { - Long parentDirectoryId = new Long(rs.getLong("parent_directory_id")); - Directory parentDirectory = Directory.ROOT_DIRECTORY; - if (parentDirectoryId != null && !parentDirectoryId.equals(new Long(-1))) { - // Need to go and lookup the parent, so do that first - parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); - } - Directory directory = new Directory(rs.getString("directory_name"), parentDirectory); - FieldUtils.setProtectedFieldValue("id", directory, new Long(rs.getLong("id"))); - return directory; - } - }); - } - - public AbstractElement[] findElements(Directory directory) { - Assert.notNull(directory, "Directory required (the ID can be null to refer to root)"); - if (directory.getId() == null) { - List directories = getJdbcTemplate().query(SELECT_FROM_DIRECTORY_NULL, new RowMapper() { - public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { - return getDirectoryWithImmediateParentPopulated(new Long(rs.getLong("id"))); - } - }); - return (AbstractElement[]) directories.toArray(new AbstractElement[] {}); - } - List directories = getJdbcTemplate().query(SELECT_FROM_DIRECTORY, new Object[] {directory.getId()}, new RowMapper() { - public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { - return getDirectoryWithImmediateParentPopulated(new Long(rs.getLong("id"))); - } - }); - List files = getJdbcTemplate().query(SELECT_FROM_FILE, new Object[] {directory.getId()}, new RowMapper() { - public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { - Long parentDirectoryId = new Long(rs.getLong("parent_directory_id")); - Directory parentDirectory = null; - if (parentDirectoryId != null) { - parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); - } - File file = new File(rs.getString("file_name"), parentDirectory); - FieldUtils.setProtectedFieldValue("id", file, new Long(rs.getLong("id"))); - return file; - } - }); - // Add the File elements after the Directory elements - directories.addAll(files); - return (AbstractElement[]) directories.toArray(new AbstractElement[] {}); - } + public void delete(File file) { + Assert.notNull(file, "File required"); + Assert.notNull(file.getId(), "File ID required"); + getJdbcTemplate().update(DELETE_FROM_FILE, new Object[] {file.getId()}); + } - public void update(File file) { - Assert.notNull(file, "File required"); - Assert.notNull(file.getId(), "File ID required"); - getJdbcTemplate().update(UPDATE_FILE, new Object[] {file.getContent(), file.getId()}); - } + /** Executes recursive SQL as needed to build a full Directory hierarchy of objects */ + private Directory getDirectoryWithImmediateParentPopulated(final Long id) { + return (Directory) getJdbcTemplate().queryForObject(SELECT_FROM_DIRECTORY_SINGLE, new Object[] {id}, new RowMapper() { + public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { + Long parentDirectoryId = new Long(rs.getLong("parent_directory_id")); + Directory parentDirectory = Directory.ROOT_DIRECTORY; + if (parentDirectoryId != null && !parentDirectoryId.equals(new Long(-1))) { + // Need to go and lookup the parent, so do that first + parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); + } + Directory directory = new Directory(rs.getString("directory_name"), parentDirectory); + FieldUtils.setProtectedFieldValue("id", directory, new Long(rs.getLong("id"))); + return directory; + } + }); + } + + public AbstractElement[] findElements(Directory directory) { + Assert.notNull(directory, "Directory required (the ID can be null to refer to root)"); + if (directory.getId() == null) { + List directories = getJdbcTemplate().query(SELECT_FROM_DIRECTORY_NULL, new RowMapper() { + public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { + return getDirectoryWithImmediateParentPopulated(new Long(rs.getLong("id"))); + } + }); + return (AbstractElement[]) directories.toArray(new AbstractElement[] {}); + } + List directories = getJdbcTemplate().query(SELECT_FROM_DIRECTORY, new Object[] {directory.getId()}, new RowMapper() { + public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { + return getDirectoryWithImmediateParentPopulated(new Long(rs.getLong("id"))); + } + }); + List files = getJdbcTemplate().query(SELECT_FROM_FILE, new Object[] {directory.getId()}, new RowMapper() { + public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { + Long parentDirectoryId = new Long(rs.getLong("parent_directory_id")); + Directory parentDirectory = null; + if (parentDirectoryId != null) { + parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); + } + File file = new File(rs.getString("file_name"), parentDirectory); + FieldUtils.setProtectedFieldValue("id", file, new Long(rs.getLong("id"))); + return file; + } + }); + // Add the File elements after the Directory elements + directories.addAll(files); + return (AbstractElement[]) directories.toArray(new AbstractElement[] {}); + } + + public void update(File file) { + Assert.notNull(file, "File required"); + Assert.notNull(file.getId(), "File ID required"); + getJdbcTemplate().update(UPDATE_FILE, new Object[] {file.getContent(), file.getId()}); + } } diff --git a/samples/dms/src/main/java/sample/dms/File.java b/samples/dms/src/main/java/sample/dms/File.java index f5e664a50e..968a52a269 100755 --- a/samples/dms/src/main/java/sample/dms/File.java +++ b/samples/dms/src/main/java/sample/dms/File.java @@ -4,29 +4,29 @@ import org.springframework.util.Assert; /** - * + * * @author Ben Alex * @version $Id$ */ public class File extends AbstractElement { - /** Content of the file, which can be null */ - private String content; - - public File(String name, Directory parent) { - super(name, parent); - Assert.isTrue(!parent.equals(Directory.ROOT_DIRECTORY), "Cannot insert File into root directory"); - } + /** Content of the file, which can be null */ + private String content; - public String getContent() { - return content; - } + public File(String name, Directory parent) { + super(name, parent); + Assert.isTrue(!parent.equals(Directory.ROOT_DIRECTORY), "Cannot insert File into root directory"); + } - public void setContent(String content) { - this.content = content; - } - - public String toString() { - return "File[fullName='" + getFullName() + "'; name='" + getName() + "'; id='" + getId() + "'; content=" + getContent() + "'; parent='" + getParent() + "']"; - } + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String toString() { + return "File[fullName='" + getFullName() + "'; name='" + getName() + "'; id='" + getId() + "'; content=" + getContent() + "'; parent='" + getParent() + "']"; + } } diff --git a/samples/dms/src/main/java/sample/dms/secured/SecureDataSourcePopulator.java b/samples/dms/src/main/java/sample/dms/secured/SecureDataSourcePopulator.java index 0187892d6d..65137c8e69 100755 --- a/samples/dms/src/main/java/sample/dms/secured/SecureDataSourcePopulator.java +++ b/samples/dms/src/main/java/sample/dms/secured/SecureDataSourcePopulator.java @@ -22,67 +22,67 @@ import sample.dms.DocumentDao; public class SecureDataSourcePopulator extends DataSourcePopulator { - private MutableAclService aclService; - - public SecureDataSourcePopulator(DataSource dataSource, SecureDocumentDao documentDao, PlatformTransactionManager platformTransactionManager, MutableAclService aclService) { - super(dataSource, documentDao, platformTransactionManager); - Assert.notNull(aclService, "MutableAclService required"); - this.aclService = aclService; - } + private MutableAclService aclService; + + public SecureDataSourcePopulator(DataSource dataSource, SecureDocumentDao documentDao, PlatformTransactionManager platformTransactionManager, MutableAclService aclService) { + super(dataSource, documentDao, platformTransactionManager); + Assert.notNull(aclService, "MutableAclService required"); + this.aclService = aclService; + } + + protected void addPermission(DocumentDao documentDao, AbstractElement element, String recipient, int level) { + Assert.notNull(documentDao, "DocumentDao required"); + Assert.isInstanceOf(SecureDocumentDao.class, documentDao, "DocumentDao should have been a SecureDocumentDao"); + Assert.notNull(element, "Element required"); + Assert.hasText(recipient, "Recipient required"); + Assert.notNull(SecurityContextHolder.getContext().getAuthentication(), "SecurityContextHolder must contain an Authentication"); + + // We need SecureDocumentDao to assign different permissions + SecureDocumentDao dao = (SecureDocumentDao) documentDao; + + // We need to construct an ACL-specific Sid. Note the prefix contract is defined on the superclass method's JavaDocs + Sid sid = null; + if (recipient.startsWith("ROLE_")) { + sid = new GrantedAuthoritySid(recipient); + } else { + sid = new PrincipalSid(recipient); + } + + // We need to identify the target domain object and create an ObjectIdentity for it + // This works because AbstractElement has a "getId()" method + ObjectIdentity identity = new ObjectIdentityImpl(element); + // ObjectIdentity identity = new ObjectIdentityImpl(element.getClass(), element.getId()); // equivalent + + // Next we need to create a Permission + Permission permission = null; + if (level == LEVEL_NEGATE_READ || level == LEVEL_GRANT_READ) { + permission = BasePermission.READ; + } else if (level == LEVEL_GRANT_WRITE) { + permission = BasePermission.WRITE; + } else if (level == LEVEL_GRANT_ADMIN) { + permission = BasePermission.ADMINISTRATION; + } else { + throw new IllegalArgumentException("Unsupported LEVEL_"); + } + + // Attempt to retrieve the existing ACL, creating an ACL if it doesn't already exist for this ObjectIdentity + MutableAcl acl = null; + try { + acl = (MutableAcl) aclService.readAclById(identity); + } catch (NotFoundException nfe) { + acl = aclService.createAcl(identity); + Assert.notNull(acl, "Acl could not be retrieved or created"); + } + + // Now we have an ACL, add another ACE to it + if (level == LEVEL_NEGATE_READ) { + acl.insertAce(null, permission, sid, false); // not granting + } else { + acl.insertAce(null, permission, sid, true); // granting + } + + // Finally, persist the modified ACL + aclService.updateAcl(acl); + } - protected void addPermission(DocumentDao documentDao, AbstractElement element, String recipient, int level) { - Assert.notNull(documentDao, "DocumentDao required"); - Assert.isInstanceOf(SecureDocumentDao.class, documentDao, "DocumentDao should have been a SecureDocumentDao"); - Assert.notNull(element, "Element required"); - Assert.hasText(recipient, "Recipient required"); - Assert.notNull(SecurityContextHolder.getContext().getAuthentication(), "SecurityContextHolder must contain an Authentication"); - - // We need SecureDocumentDao to assign different permissions - SecureDocumentDao dao = (SecureDocumentDao) documentDao; - - // We need to construct an ACL-specific Sid. Note the prefix contract is defined on the superclass method's JavaDocs - Sid sid = null; - if (recipient.startsWith("ROLE_")) { - sid = new GrantedAuthoritySid(recipient); - } else { - sid = new PrincipalSid(recipient); - } - - // We need to identify the target domain object and create an ObjectIdentity for it - // This works because AbstractElement has a "getId()" method - ObjectIdentity identity = new ObjectIdentityImpl(element); - // ObjectIdentity identity = new ObjectIdentityImpl(element.getClass(), element.getId()); // equivalent - - // Next we need to create a Permission - Permission permission = null; - if (level == LEVEL_NEGATE_READ || level == LEVEL_GRANT_READ) { - permission = BasePermission.READ; - } else if (level == LEVEL_GRANT_WRITE) { - permission = BasePermission.WRITE; - } else if (level == LEVEL_GRANT_ADMIN) { - permission = BasePermission.ADMINISTRATION; - } else { - throw new IllegalArgumentException("Unsupported LEVEL_"); - } - - // Attempt to retrieve the existing ACL, creating an ACL if it doesn't already exist for this ObjectIdentity - MutableAcl acl = null; - try { - acl = (MutableAcl) aclService.readAclById(identity); - } catch (NotFoundException nfe) { - acl = aclService.createAcl(identity); - Assert.notNull(acl, "Acl could not be retrieved or created"); - } - - // Now we have an ACL, add another ACE to it - if (level == LEVEL_NEGATE_READ) { - acl.insertAce(null, permission, sid, false); // not granting - } else { - acl.insertAce(null, permission, sid, true); // granting - } - - // Finally, persist the modified ACL - aclService.updateAcl(acl); - } - } diff --git a/samples/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java b/samples/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java index 5a06d0d436..a6effdac99 100755 --- a/samples/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java +++ b/samples/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java @@ -18,44 +18,44 @@ import sample.dms.DocumentDaoImpl; /** * Adds extra {@link SecureDocumentDao} methods. - * + * * @author Ben Alex * @version $Id$ * */ public class SecureDocumentDaoImpl extends DocumentDaoImpl implements SecureDocumentDao { - private static final String SELECT_FROM_USERS = "SELECT USERNAME FROM USERS ORDER BY USERNAME"; - private MutableAclService mutableAclService; - - public SecureDocumentDaoImpl(MutableAclService mutableAclService) { - Assert.notNull(mutableAclService, "MutableAclService required"); - this.mutableAclService = mutableAclService; - } - - public String[] getUsers() { - return (String[]) getJdbcTemplate().query(SELECT_FROM_USERS, new RowMapper() { - public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { - return rs.getString("USERNAME"); - } - }).toArray(new String[] {}); - } + private static final String SELECT_FROM_USERS = "SELECT USERNAME FROM USERS ORDER BY USERNAME"; + private MutableAclService mutableAclService; - public void create(AbstractElement element) { - super.create(element); + public SecureDocumentDaoImpl(MutableAclService mutableAclService) { + Assert.notNull(mutableAclService, "MutableAclService required"); + this.mutableAclService = mutableAclService; + } - // Create an ACL identity for this element - ObjectIdentity identity = new ObjectIdentityImpl(element); - MutableAcl acl = mutableAclService.createAcl(identity); - - // If the AbstractElement has a parent, go and retrieve its identity (it should already exist) - if (element.getParent() != null) { - ObjectIdentity parentIdentity = new ObjectIdentityImpl(element.getParent()); - MutableAcl aclParent = (MutableAcl) mutableAclService.readAclById(parentIdentity); - acl.setParent(aclParent); - } - acl.insertAce(null, BasePermission.ADMINISTRATION, new PrincipalSid(SecurityContextHolder.getContext().getAuthentication()), true); - - mutableAclService.updateAcl(acl); - } + public String[] getUsers() { + return (String[]) getJdbcTemplate().query(SELECT_FROM_USERS, new RowMapper() { + public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { + return rs.getString("USERNAME"); + } + }).toArray(new String[] {}); + } + + public void create(AbstractElement element) { + super.create(element); + + // Create an ACL identity for this element + ObjectIdentity identity = new ObjectIdentityImpl(element); + MutableAcl acl = mutableAclService.createAcl(identity); + + // If the AbstractElement has a parent, go and retrieve its identity (it should already exist) + if (element.getParent() != null) { + ObjectIdentity parentIdentity = new ObjectIdentityImpl(element.getParent()); + MutableAcl aclParent = (MutableAcl) mutableAclService.readAclById(parentIdentity); + acl.setParent(aclParent); + } + acl.insertAce(null, BasePermission.ADMINISTRATION, new PrincipalSid(SecurityContextHolder.getContext().getAuthentication()), true); + + mutableAclService.updateAcl(acl); + } } diff --git a/samples/dms/src/test/java/DmsIntegrationTests.java b/samples/dms/src/test/java/DmsIntegrationTests.java index 8e65d312be..4cbf4ea5d3 100755 --- a/samples/dms/src/test/java/DmsIntegrationTests.java +++ b/samples/dms/src/test/java/DmsIntegrationTests.java @@ -8,80 +8,80 @@ import sample.dms.DocumentDao; /** * Basic integration test for DMS sample. - * + * * @author Ben Alex * @version $Id$ * */ public class DmsIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests { - protected DocumentDao documentDao; - - protected String[] getConfigLocations() { - return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-insecure.xml"}; - } + protected DocumentDao documentDao; - public void setDocumentDao(DocumentDao documentDao) { - this.documentDao = documentDao; - } + protected String[] getConfigLocations() { + return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-insecure.xml"}; + } - public void testBasePopulation() { - assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY")); - assertEquals(90, jdbcTemplate.queryForInt("select count(id) from FILE")); - assertEquals(3, documentDao.findElements(Directory.ROOT_DIRECTORY).length); - } - - public void testMarissaRetrieval() { - process("marissa", "koala", false); - } - - public void testScottRetrieval() { - process("scott", "wombat", false); - } - - public void testDianneRetrieval() { - process("dianne", "emu", false); - } + public void setDocumentDao(DocumentDao documentDao) { + this.documentDao = documentDao; + } - protected void process(String username, String password, boolean shouldBeFiltered) { - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username, password)); - System.out.println("------ Test for username: " + username + " ------"); - AbstractElement[] rootElements = documentDao.findElements(Directory.ROOT_DIRECTORY); - assertEquals(3, rootElements.length); - Directory homeDir = null; - Directory nonHomeDir = null; - for (int i = 0; i < rootElements.length; i++) { - if (rootElements[i].getName().equals(username)) { - homeDir = (Directory) rootElements[i]; - } else { - nonHomeDir = (Directory) rootElements[i]; - } - } - System.out.println("Home directory......: " + homeDir.getFullName()); - System.out.println("Non-home directory..: " + nonHomeDir.getFullName()); - - AbstractElement[] homeElements = documentDao.findElements(homeDir); - assertEquals(12, homeElements.length); // confidential and shared directories, plus 10 files + public void testBasePopulation() { + assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY")); + assertEquals(90, jdbcTemplate.queryForInt("select count(id) from FILE")); + assertEquals(3, documentDao.findElements(Directory.ROOT_DIRECTORY).length); + } + + public void testMarissaRetrieval() { + process("marissa", "koala", false); + } + + public void testScottRetrieval() { + process("scott", "wombat", false); + } + + public void testDianneRetrieval() { + process("dianne", "emu", false); + } + + protected void process(String username, String password, boolean shouldBeFiltered) { + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username, password)); + System.out.println("------ Test for username: " + username + " ------"); + AbstractElement[] rootElements = documentDao.findElements(Directory.ROOT_DIRECTORY); + assertEquals(3, rootElements.length); + Directory homeDir = null; + Directory nonHomeDir = null; + for (int i = 0; i < rootElements.length; i++) { + if (rootElements[i].getName().equals(username)) { + homeDir = (Directory) rootElements[i]; + } else { + nonHomeDir = (Directory) rootElements[i]; + } + } + System.out.println("Home directory......: " + homeDir.getFullName()); + System.out.println("Non-home directory..: " + nonHomeDir.getFullName()); + + AbstractElement[] homeElements = documentDao.findElements(homeDir); + assertEquals(12, homeElements.length); // confidential and shared directories, plus 10 files + + AbstractElement[] nonHomeElements = documentDao.findElements(nonHomeDir); + assertEquals(shouldBeFiltered ? 11 : 12, nonHomeElements.length); // cannot see the user's "confidential" sub-directory when filtering + + // Attempt to read the other user's confidential directory from the returned results + // Of course, we shouldn't find a "confidential" directory in the results if we're filtering + Directory nonHomeConfidentialDir = null; + for (int i = 0; i < nonHomeElements.length; i++) { + if (nonHomeElements[i].getName().equals("confidential")) { + nonHomeConfidentialDir = (Directory) nonHomeElements[i]; + } + } + + if (shouldBeFiltered) { + assertNull("Found confidential directory when we should not have", nonHomeConfidentialDir); + } else { + System.out.println("Inaccessible dir....: " + nonHomeConfidentialDir.getFullName()); + assertEquals(10, documentDao.findElements(nonHomeConfidentialDir).length); // 10 files (no sub-directories) + } + + SecurityContextHolder.clearContext(); + } - AbstractElement[] nonHomeElements = documentDao.findElements(nonHomeDir); - assertEquals(shouldBeFiltered ? 11 : 12, nonHomeElements.length); // cannot see the user's "confidential" sub-directory when filtering - - // Attempt to read the other user's confidential directory from the returned results - // Of course, we shouldn't find a "confidential" directory in the results if we're filtering - Directory nonHomeConfidentialDir = null; - for (int i = 0; i < nonHomeElements.length; i++) { - if (nonHomeElements[i].getName().equals("confidential")) { - nonHomeConfidentialDir = (Directory) nonHomeElements[i]; - } - } - - if (shouldBeFiltered) { - assertNull("Found confidential directory when we should not have", nonHomeConfidentialDir); - } else { - System.out.println("Inaccessible dir....: " + nonHomeConfidentialDir.getFullName()); - assertEquals(10, documentDao.findElements(nonHomeConfidentialDir).length); // 10 files (no sub-directories) - } - - SecurityContextHolder.clearContext(); - } - } diff --git a/samples/dms/src/test/java/SecureDmsIntegrationTests.java b/samples/dms/src/test/java/SecureDmsIntegrationTests.java index e49fa349ac..1f1c527fde 100755 --- a/samples/dms/src/test/java/SecureDmsIntegrationTests.java +++ b/samples/dms/src/test/java/SecureDmsIntegrationTests.java @@ -14,54 +14,54 @@ import sample.dms.Directory; /** * Basic integration test for DMS sample when security has been added. - * + * * @author Ben Alex * @version $Id$ * */ public class SecureDmsIntegrationTests extends DmsIntegrationTests { - private AclService aclService; - - public void setAclService(AclService aclService) { - this.aclService = aclService; - } + private AclService aclService; - protected String[] getConfigLocations() { - return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-secure.xml"}; - } + public void setAclService(AclService aclService) { + this.aclService = aclService; + } - public void testBasePopulation() { - assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY")); - assertEquals(90, jdbcTemplate.queryForInt("select count(id) from FILE")); - assertEquals(4, jdbcTemplate.queryForInt("select count(id) from ACL_SID")); // 3 users + 1 role - assertEquals(2, jdbcTemplate.queryForInt("select count(id) from ACL_CLASS")); // Directory and File - assertEquals(100, jdbcTemplate.queryForInt("select count(id) from ACL_OBJECT_IDENTITY")); - assertEquals(115, jdbcTemplate.queryForInt("select count(id) from ACL_ENTRY")); - } - /* - public void testItOut() { - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("marissa", "password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SUPERVISOR")})); - - - AbstractElement[] elements = documentDao.findElements(Directory.ROOT_DIRECTORY); - ObjectIdentity oid = new ObjectIdentityImpl(elements[0]); - //ObjectIdentity oid = new ObjectIdentityImpl(Directory.class, new Long(3)); - Acl acl = aclService.readAclById(oid); - System.out.println(acl); - - }*/ - - public void testMarissaRetrieval() { - process("marissa", "koala", true); - } + protected String[] getConfigLocations() { + return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-secure.xml"}; + } - - public void testScottRetrieval() { - process("scott", "wombat", true); - } - - public void testDianneRetrieval() { - process("dianne", "emu", true); - } + public void testBasePopulation() { + assertEquals(9, jdbcTemplate.queryForInt("select count(id) from DIRECTORY")); + assertEquals(90, jdbcTemplate.queryForInt("select count(id) from FILE")); + assertEquals(4, jdbcTemplate.queryForInt("select count(id) from ACL_SID")); // 3 users + 1 role + assertEquals(2, jdbcTemplate.queryForInt("select count(id) from ACL_CLASS")); // Directory and File + assertEquals(100, jdbcTemplate.queryForInt("select count(id) from ACL_OBJECT_IDENTITY")); + assertEquals(115, jdbcTemplate.queryForInt("select count(id) from ACL_ENTRY")); + } + /* + public void testItOut() { + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("marissa", "password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SUPERVISOR")})); + + + AbstractElement[] elements = documentDao.findElements(Directory.ROOT_DIRECTORY); + ObjectIdentity oid = new ObjectIdentityImpl(elements[0]); + //ObjectIdentity oid = new ObjectIdentityImpl(Directory.class, new Long(3)); + Acl acl = aclService.readAclById(oid); + System.out.println(acl); + + }*/ + + public void testMarissaRetrieval() { + process("marissa", "koala", true); + } + + + public void testScottRetrieval() { + process("scott", "wombat", true); + } + + public void testDianneRetrieval() { + process("dianne", "emu", true); + } }