1 25 26 package org.snipsnap.user; 27 28 import java.util.*; 29 30 36 37 public class Roles { 38 private Set roleSet; 39 40 public final static String AUTHENTICATED = "Authenticated"; 41 public final static String OWNER = "Owner"; 42 public final static String ADMIN = "Admin"; 43 public final static String EDITOR = "Editor"; 44 public final static String NOCOMMENT = "NoComment"; 45 46 private static Set ROLES = null; 47 48 public static Set allRoles() { 49 if (ROLES == null) { 50 ROLES = new TreeSet(); 51 ROLES.add(EDITOR); 52 ROLES.add(ADMIN); 53 ROLES.add(NOCOMMENT); 54 ROLES = Collections.unmodifiableSet(ROLES); 55 } 56 return ROLES; 57 } 58 59 public Set getAllRoles() { 60 return Roles.allRoles(); 61 } 62 63 public Roles(Roles roles) { 64 roleSet = new HashSet(roles.roleSet); 65 } 66 67 public Roles(String roleString) { 68 this.roleSet = deserialize(roleString); 69 } 70 71 public Roles() { 72 roleSet = new HashSet(); 73 } 74 75 public Roles(Set roleSet) { 76 this.roleSet = new HashSet(roleSet); 77 } 78 79 public boolean isEmpty() { 80 return roleSet.isEmpty(); 81 } 82 83 public void remove(String role) { 84 if (roleSet.contains(role)) { 85 roleSet.remove(role); 86 } 87 } 88 89 public void add(String role) { 90 roleSet.add(role); 91 } 92 93 public void addAll(Roles roles) { 94 this.roleSet.addAll(roles.getRoleSet()); 95 } 96 97 public Iterator iterator() { 98 return roleSet.iterator(); 99 } 100 101 public boolean contains(String role) { 102 return roleSet.contains(role); 103 } 104 105 public boolean containsAny(Roles r1) { 106 Roles r2 = this; 108 Iterator iterator = r1.iterator(); 109 while (iterator.hasNext()) { 110 String s = (String ) iterator.next(); 111 if (r2.contains(s)) { return true; } 112 } 113 return false; 114 } 115 116 public Set getRoleSet() { 117 return Collections.unmodifiableSet(roleSet); 118 } 119 120 public String toString() { 121 return serialize(roleSet); 122 } 123 124 private String serialize(Set roles) { 125 if (null == roles || roles.isEmpty()) { return ""; } 126 127 StringBuffer buffer = new StringBuffer (); 128 Iterator iterator = roles.iterator(); 129 while (iterator.hasNext()) { 130 String role = (String ) iterator.next(); 131 buffer.append(role); 132 if (iterator.hasNext()) { buffer.append(":"); } 133 } 134 return buffer.toString(); 135 } 136 137 private Set deserialize(String roleString) { 138 if (null == roleString || "".equals(roleString)) { return new HashSet(); } 139 140 StringTokenizer st = new StringTokenizer(roleString, ":"); 141 Set roles = new HashSet(); 142 143 while (st.hasMoreTokens()) { 144 roles.add(st.nextToken()); 145 } 146 147 return roles; 148 } 149 150 public int hashCode() { 151 return getRoleSet().hashCode(); 152 } 153 154 public boolean equals(Roles obj) { 155 return getRoleSet().equals(obj.getRoleSet()); 156 } 157 } 158 | Popular Tags |