1 18 package net.sf.uitags.tagutil; 19 20 import java.io.Serializable ; 21 import java.util.HashMap ; 22 23 import javax.servlet.jsp.PageContext ; 24 25 34 public final class ScopedIdGenerator { 35 38 private ScopedIdGenerator() { 39 super(); 40 } 41 42 59 public static long nextId( 60 int scope, String key, PageContext pageContext, String groupId) { 61 if (scope != PageContext.PAGE_SCOPE && 63 scope != PageContext.REQUEST_SCOPE && 64 scope != PageContext.SESSION_SCOPE && 65 scope != PageContext.APPLICATION_SCOPE) { 66 throw new IllegalArgumentException ( 67 "Scope value must be one of the constants declared in PageContext."); 68 } 69 if (key == null) { 70 throw new NullPointerException ("key can't be null."); 71 } 72 73 if (scope == PageContext.PAGE_SCOPE || scope == PageContext.REQUEST_SCOPE) { 76 return nextIdVal(scope, key, pageContext, groupId); 77 } 78 else { 81 synchronized (ScopedIdGenerator.class) { 82 return nextIdVal(scope, key, pageContext, groupId); 83 } 84 } 85 } 86 87 100 public static long nextId(int scope, String key, PageContext pageContext) { 101 return nextId(scope, key, pageContext, null); 102 } 103 104 125 private static long nextIdVal( 126 int scope, String key, PageContext pageContext, String groupId) { 127 Id currId; 130 try { 131 currId = (Id) pageContext.getAttribute(key, scope); 132 } 133 catch (ClassCastException e) { 134 throw new IllegalStateException ( 135 "Cannot create an ID named '" + key + "' in scope '" + scope + "'." + 136 " Another object is occupying that spot."); 137 } 138 139 146 long newId = 1; 147 if (currId == null) { 148 currId = new Id(); 149 pageContext.setAttribute(key, currId, scope); 150 } 151 else if (currId.contains(groupId)) { 152 return currId.getValue(groupId); 153 } 154 else { 155 newId = currId.getCurrentValue() + 1; 156 } 157 158 currId.addValue(groupId, newId); 159 return newId; 160 } 161 162 167 private static final class Id implements Serializable { 168 private static final long serialVersionUID = 100L; 169 170 173 private long currentValue; 174 175 178 private HashMap valueMap; 179 180 183 private Id() { 184 this.valueMap = new HashMap (); 185 } 186 187 193 private void addValue(String groupId, long value) { 194 this.valueMap.put(groupId, new Long (value)); 195 this.currentValue = value; 196 } 197 198 204 private boolean contains(String groupId) { 205 if (groupId == null) { 207 return false; 208 } 209 return this.valueMap.containsKey(groupId); 210 } 211 212 218 private long getValue(String groupId) { 219 if (groupId == null) { 221 return this.currentValue; 222 } 223 return ((Long ) this.valueMap.get(groupId)).longValue(); 224 } 225 226 231 private long getCurrentValue() { 232 return this.currentValue; 233 } 234 } 235 } 236 | Popular Tags |