1 52 53 package freemarker.template; 54 55 import java.io.Serializable ; 56 import java.util.*; 57 58 75 public class SimpleCollection extends WrappingTemplateModel 76 implements TemplateCollectionModel, Serializable { 77 78 private boolean iteratorDirty; 79 private Iterator iterator; 80 private Collection collection; 81 82 public SimpleCollection(Iterator iterator) { 83 this.iterator = iterator; 84 } 85 86 public SimpleCollection(Collection collection) { 87 this.collection = collection; 88 } 89 90 public SimpleCollection(Iterator iterator, ObjectWrapper wrapper) { 91 super(wrapper); 92 this.iterator = iterator; 93 } 94 95 public SimpleCollection(Collection collection, ObjectWrapper wrapper) { 96 super(wrapper); 97 this.collection = collection; 98 } 99 100 109 public TemplateModelIterator iterator() { 110 if (iterator != null) { 111 return new SimpleTemplateModelIterator(iterator, true); 112 } else { 113 synchronized (collection) { 114 return new SimpleTemplateModelIterator(collection.iterator(), false); 115 } 116 } 117 } 118 119 125 private class SimpleTemplateModelIterator implements TemplateModelIterator { 126 127 private Iterator iterator; 128 private boolean iteratorShared; 129 130 SimpleTemplateModelIterator(Iterator iterator, boolean iteratorShared) { 131 this.iterator = iterator; 132 this.iteratorShared = iteratorShared; 133 } 134 135 public TemplateModel next() throws TemplateModelException { 136 if (iteratorShared) makeIteratorDirty(); 137 138 if (!iterator.hasNext()) { 139 throw new TemplateModelException("The collection has no more elements."); 140 } 141 142 Object value = iterator.next(); 143 if (value instanceof TemplateModel) { 144 return (TemplateModel) value; 145 } else { 146 return wrap(value); 147 } 148 } 149 150 public boolean hasNext() throws TemplateModelException { 151 155 if (iteratorShared) makeIteratorDirty(); 156 return iterator.hasNext(); 157 } 158 159 private void makeIteratorDirty() throws TemplateModelException { 160 synchronized (SimpleCollection.this) { 161 if (iteratorDirty) { 162 throw new TemplateModelException( 163 "This collection variable wraps a java.util.Iterator, " 164 + "thus it can be <list>-ed or <foreach>-ed only once"); 165 } else { 166 iteratorDirty = true; 167 iteratorShared = false; 168 } 169 } 170 } 171 } 172 } 173 | Popular Tags |