1 package org.sapia.validator.rules; 2 3 import org.apache.commons.beanutils.PropertyUtils; 4 import org.sapia.validator.CompositeRule; 5 import org.sapia.validator.ValidationContext; 6 7 import java.util.Collection ; 8 import java.util.Iterator ; 9 10 25 public class ForEach extends CompositeRule { 26 private String _attribute; 27 private boolean _ignoreNull; 28 29 32 public ForEach() { 33 super(); 34 } 35 36 43 public void setAttribute(String attr) { 44 _attribute = attr; 45 } 46 47 50 public void validate(ValidationContext ctx) { 51 Object obj; 52 Iterator items; 53 54 if (_attribute == null) { 55 obj = ctx.get(); 56 57 if (obj == null) { 58 throw new IllegalStateException ("No object on validation context stack at " + qualifiedName()); 59 } 60 } else { 61 try { 62 if (ctx.get() == null) { 63 throw new IllegalStateException ( 64 "No object on validation context stack at " + qualifiedName()); 65 } 66 67 obj = PropertyUtils.getProperty(ctx.get(), _attribute); 68 69 if (obj == null) { 70 throw new IllegalStateException ("Attribute " + _attribute 71 + " evaluates to null at " + qualifiedName()); 72 } 73 } catch (Throwable err) { 74 ctx.getStatus().error(this, err); 75 76 return; 77 } 78 } 79 80 if (obj instanceof Collection ) { 81 items = ((Collection ) obj).iterator(); 82 } else if (obj instanceof Object []) { 83 items = new ArrayIterator((Object []) obj); 84 } else if (obj instanceof Iterator ) { 85 items = (Iterator ) obj; 86 } else { 87 throw new IllegalStateException ( 88 "forEach rule processes instances of java.util.Collection, java.util.Iterator, or arrays at " + qualifiedName()); 89 } 90 91 if (items == null) { 92 return; 93 } 94 95 Object item; 96 boolean valid = true; 97 98 for (; items.hasNext();) { 99 item = items.next(); 100 ctx.push(item); 101 super.validate(ctx); 102 103 if (ctx.getStatus().isError() && _stop) { 104 ctx.pop(); 105 106 break; 107 } 108 109 ctx.pop(); 110 } 111 } 112 113 static class ArrayIterator implements Iterator { 114 int _count; 115 Object [] _array; 116 117 ArrayIterator(Object [] array) { 118 _array = array; 119 } 120 121 124 public boolean hasNext() { 125 return _count < _array.length; 126 } 127 128 131 public Object next() { 132 return _array[_count++]; 133 } 134 135 138 public void remove() { 139 } 140 } 141 } 142 | Popular Tags |