1 16 17 package org.apache.taglibs.standard.lang.jpath.adapter; 18 19 import java.util.ArrayList ; 20 import java.util.Collection ; 21 import java.util.Iterator ; 22 23 import javax.servlet.jsp.PageContext ; 24 25 import org.apache.taglibs.standard.lang.jpath.expression.EvaluationException; 26 import org.apache.taglibs.standard.lang.jpath.expression.Expression; 27 import org.apache.taglibs.standard.lang.jpath.expression.Predicate; 28 29 public class CollectionAdapter extends JSPAdapter implements JSPList { 30 31 private Expression predicate; 32 33 private Iterator iterator; 34 private int size; 35 private int position; 36 private Object current; 37 38 public Object next() { 39 position++; 40 current = iterator.next(); 41 return current; 42 } 43 44 public Object getCurrent() { 45 return current; 46 } 47 48 public boolean hasNext() { 49 return iterator.hasNext(); 50 } 51 52 public int getPosition() { 53 return position; 54 } 55 56 public int getLast() { 57 return size; 58 } 59 60 private void setCollection(Collection c) { 61 this.iterator = c.iterator(); 62 this.size = c.size(); 63 this.position = 0; 64 } 65 66 public boolean applyPredicate(PageContext pageContext, Predicate predicate) throws ConversionException, EvaluationException { 67 boolean oneItem = false; 68 Object result; 69 boolean predicateTrue; 70 if (position != 0) { 71 throw new ConversionException("You cannot apply a predicate to " 72 + "a JSPList that has begun to be iterated"); 73 } 74 Collection predicated = new ArrayList (); 75 while (iterator.hasNext()) { 76 this.next(); 77 result = predicate.evaluate(pageContext, new JSPListIterationContext(this)); 78 if (result instanceof Double ) { 79 oneItem = true; 80 predicateTrue = ((Double )result).doubleValue() == position; 81 } else { 82 oneItem = false; 83 predicateTrue = Convert.toBoolean(result).booleanValue(); 84 } 85 if (predicateTrue) { 86 predicated.add(current); 87 } 88 } 89 this.iterator = predicated.iterator(); 90 this.size = predicated.size(); 91 this.position = 0; 92 return oneItem; 93 } 94 95 public static Object adapt(Object o) { 96 CollectionAdapter adapter = new CollectionAdapter(); 97 adapter.setCollection((Collection )o); 98 return adapter; 99 } 100 101 public static Class [] getAdaptedClasses() { 102 Class [] adaptedClasses = {Collection .class}; 103 return adaptedClasses; 104 } 105 106 public void remove() { 107 throw new UnsupportedOperationException (); 108 } 109 110 111 } 112 | Popular Tags |