1 /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.springframework.security;
17
18 import java.io.Serializable;
19
20 import org.springframework.util.Assert;
21
22
23 /**
24 * Basic concrete implementation of a {@link GrantedAuthority}.
25 *
26 * <p>
27 * Stores a <code>String</code> representation of an authority granted to the {@link Authentication} object.
28 * <p>
29 * If compared to a custom authority which returns null from {@link #getAuthority}, the <tt>compareTo</tt>
30 * method will return -1, so the custom authority will take precedence.
31 *
32 * @author Ben Alex
33 * @version $Id: GrantedAuthorityImpl.java 3197 2008-07-31 13:01:22Z luke_t $
34 */
35 public class GrantedAuthorityImpl implements GrantedAuthority, Serializable {
36 //~ Instance fields ================================================================================================
37
38 private static final long serialVersionUID = 1L;
39 private String role;
40
41 //~ Constructors ===================================================================================================
42
43 public GrantedAuthorityImpl(String role) {
44 Assert.hasText(role, "A granted authority textual representation is required");
45 this.role = role;
46 }
47
48 //~ Methods ========================================================================================================
49
50 public boolean equals(Object obj) {
51 if (obj instanceof String) {
52 return obj.equals(this.role);
53 }
54
55 if (obj instanceof GrantedAuthority) {
56 GrantedAuthority attr = (GrantedAuthority) obj;
57
58 return this.role.equals(attr.getAuthority());
59 }
60
61 return false;
62 }
63
64 public String getAuthority() {
65 return this.role;
66 }
67
68 public int hashCode() {
69 return this.role.hashCode();
70 }
71
72 public String toString() {
73 return this.role;
74 }
75
76 public int compareTo(Object o) {
77 if (o != null && o instanceof GrantedAuthority) {
78 String rhsRole = ((GrantedAuthority) o).getAuthority();
79
80 if (rhsRole == null) {
81 return -1;
82 }
83
84 return role.compareTo(rhsRole);
85 }
86 return -1;
87 }
88 }