1 16 package org.apache.commons.jelly.expression; 17 18 import java.util.Collections ; 19 import java.util.Collection ; 20 import java.util.Enumeration ; 21 import java.util.Iterator ; 22 import java.util.List ; 23 import java.util.Map ; 24 25 import org.apache.commons.collections.iterators.ArrayIterator; 26 import org.apache.commons.collections.iterators.EnumerationIterator; 27 import org.apache.commons.collections.iterators.SingletonIterator; 28 29 import org.apache.commons.jelly.JellyContext; 30 import org.apache.commons.lang.StringUtils; 31 32 40 public abstract class ExpressionSupport implements Expression { 41 42 protected static final Iterator EMPTY_ITERATOR = Collections.EMPTY_LIST.iterator(); 43 44 public String evaluateAsString(JellyContext context) { 46 Object value = evaluateRecurse(context); 47 52 if ( value != null ) { 53 return value.toString(); 54 } 55 return null; 56 } 57 58 59 public Object evaluateRecurse(JellyContext context) { 61 Object value = evaluate(context); 62 if (value instanceof Expression) { 63 Expression expression = (Expression) value; 64 return expression.evaluateRecurse(context); 65 } 66 return value; 67 } 68 69 public boolean evaluateAsBoolean(JellyContext context) { 71 Object value = evaluateRecurse(context); 72 if ( value instanceof Boolean ) { 73 Boolean b = (Boolean ) value; 74 return b.booleanValue(); 75 } 76 else if ( value instanceof String ) { 77 String str = (String ) value; 79 80 return ( str.equalsIgnoreCase( "on" ) 81 || 82 str.equalsIgnoreCase( "yes" ) 83 || 84 str.equals( "1" ) 85 || 86 str.equalsIgnoreCase( "true" ) ); 87 88 } 89 return false; 90 } 91 92 public Iterator evaluateAsIterator(JellyContext context) { 94 Object value = evaluateRecurse(context); 95 if ( value == null ) { 96 return EMPTY_ITERATOR; 97 } else if ( value instanceof Iterator ) { 98 return (Iterator ) value; 99 } else if ( value instanceof List ) { 100 List list = (List ) value; 101 return list.iterator(); 102 } else if ( value instanceof Map ) { 103 Map map = (Map ) value; 104 return map.entrySet().iterator(); 105 } else if ( value.getClass().isArray() ) { 106 return new ArrayIterator( value ); 107 } else if ( value instanceof Enumeration ) { 108 return new EnumerationIterator((Enumeration ) value); 109 } else if ( value instanceof Collection ) { 110 Collection collection = (Collection ) value; 111 return collection.iterator(); 112 } else if ( value instanceof String ) { 113 String [] array = StringUtils.split((String ) value, "," ); 114 array = StringUtils.stripAll( array ); 115 return new ArrayIterator( array ); 116 } else { 117 return new SingletonIterator( value ); 119 } 120 } 121 } 122 | Popular Tags |