1 23 24 package javax.servlet.jsp.jstl.core; 25 26 import java.util.Iterator ; 27 import java.util.Collection ; 28 import java.util.Enumeration ; 29 import java.util.Map ; 30 import java.util.StringTokenizer ; 31 32 import javax.el.ELContext; 33 import javax.el.ELException; 34 import javax.el.ValueExpression; 35 36 import javax.servlet.jsp.JspTagException ; 37 38 import org.apache.taglibs.standard.resources.Resources; 39 40 44 public final class IteratedExpression { 45 46 private static final long serialVersionUID = 1L; 47 protected final ValueExpression orig; 48 protected final String delims; 49 50 private Object base; 51 private int index; 52 private Iterator iter; 53 54 public IteratedExpression(ValueExpression orig, String delims) { 55 this.orig = orig; 56 this.delims = delims; 57 } 58 59 64 public Object getItem(ELContext context, int i) { 65 66 if (base == null) { 67 base = orig.getValue(context); 68 if (base == null) { 69 return null; 70 } 71 iter = toIterator(base); 72 index = 0; 73 } 74 if (index > i) { 75 iter = toIterator(base); 77 index = 0; 78 } 79 while (iter.hasNext()) { 80 Object item = iter.next(); 81 if (index++ == i) { 82 return item; 83 } 84 } 85 return null; 86 } 87 88 public ValueExpression getValueExpression() { 89 return orig; 90 } 91 92 private Iterator toIterator(final Object obj) { 93 94 Iterator iter; 95 if (obj instanceof String ) { 96 iter = toIterator(new StringTokenizer ((String )obj, delims)); 97 } 98 else if (obj instanceof Iterator ) { 99 iter = (Iterator )obj; 100 } 101 else if (obj instanceof Collection ) { 102 iter = toIterator(((Collection ) obj).iterator()); 103 } 104 else if (obj instanceof Enumeration ) { 105 iter = toIterator((Enumeration )obj); 106 } 107 else if (obj instanceof Map ) { 108 iter = ((Map )obj).entrySet().iterator(); 109 } else { 110 throw new ELException(Resources.getMessage("FOREACH_BAD_ITEMS")); 111 } 112 return iter; 113 } 114 115 private Iterator toIterator(final Enumeration obj) { 116 return new Iterator () { 117 public boolean hasNext() { 118 return obj.hasMoreElements(); 119 } 120 public Object next() { 121 return obj.nextElement(); 122 } 123 public void remove() {} 124 }; 125 } 126 } 127 128 | Popular Tags |