| 1 package org.sapia.soto.state.control; 2 3 import org.apache.commons.jexl.Expression; 4 import org.apache.commons.jexl.ExpressionFactory; 5 import org.apache.commons.lang.ClassUtils; 6 import org.apache.commons.lang.StringUtils; 7 8 import org.sapia.soto.state.Result; 9 import org.sapia.soto.state.ScopeMap; 10 import org.sapia.soto.state.Step; 11 import org.sapia.soto.state.helpers.CompositeStep; 12 13 import java.util.ArrayList ; 14 import java.util.List ; 15 import java.util.Map ; 16 17 18 26 public class Choose implements Step { 27 private List _cases = new ArrayList (); 28 private Otherwise _other; 29 30 33 public Choose() { 34 } 35 36 39 public String getName() { 40 return ClassUtils.getShortClassName(getClass()); 41 } 42 43 public When createWhen() { 44 When caseObj = new When(); 45 _cases.add(caseObj); 46 47 return caseObj; 48 } 49 50 public Otherwise createOtherwise() { 51 return _other = new Otherwise(); 52 } 53 54 57 public void execute(Result st) { 58 When caseObj; 59 60 for (int i = 0; i < _cases.size(); i++) { 61 caseObj = (When) _cases.get(i); 62 63 if (caseObj.isTrue(st)) { 64 caseObj.execute(st); 65 66 return; 67 } 68 } 69 70 if (_other != null) { 71 _other.execute(st); 72 } 73 } 74 75 public static class Otherwise extends CompositeStep { 77 80 public String getName() { 81 return ClassUtils.getShortClassName(getClass()); 82 } 83 84 87 protected boolean doExecute(Result st) { 88 return true; 89 } 90 } 91 92 public class When extends CompositeStep { 93 private Expression _expr; 94 private String [] _scopes; 95 96 public When() { 97 } 98 99 102 public String getName() { 103 return ClassUtils.getShortClassName(getClass()); 104 } 105 106 public boolean isTrue(Result st) { 107 Map scopes = st.getContext().getScopes(); 108 ScopeMap map = new ScopeMap(scopes, _scopes); 109 Object evaled = null; 110 111 try { 112 evaled = _expr.evaluate(map); 113 114 Boolean b = (Boolean ) evaled; 115 116 return b.booleanValue(); 117 } catch (ClassCastException e) { 118 st.error("'case' must evaluate to a Boolean, not a " + evaled); 119 120 return false; 121 } catch (Exception e) { 122 e.printStackTrace(); 123 st.error("Could not evaluate: '" + _expr.getExpression() + "' - " + 124 e.getMessage()); 125 126 return false; 127 } 128 } 129 130 public void setTest(String expr) throws Exception { 131 _expr = ExpressionFactory.createExpression(expr); 132 } 133 134 public void setScopes(String scopes) { 135 _scopes = StringUtils.split(scopes, ","); 136 137 for (int i = 0; i < _scopes.length; i++) { 138 _scopes[i] = _scopes[i].trim(); 139 } 140 } 141 142 145 protected boolean doExecute(Result st) { 146 return true; 147 } 148 } 149 } 150 | Popular Tags |