1 16 package scriptella.core; 17 18 import scriptella.configuration.Location; 19 import scriptella.configuration.ScriptingElement; 20 import scriptella.expression.Expression; 21 22 import java.util.LinkedHashSet ; 23 import java.util.Set ; 24 import java.util.logging.Level ; 25 import java.util.logging.Logger ; 26 27 28 35 public class IfInterceptor extends ElementInterceptor { 36 private static final Logger LOG = Logger.getLogger(IfInterceptor.class.getName()); 37 private static final Set <CharSequence > trueStrs = new LinkedHashSet <CharSequence >(); 38 39 static { 40 trueStrs.add("true"); 41 trueStrs.add("yes"); 42 trueStrs.add("1"); 43 trueStrs.add("on"); 44 } 45 46 private Expression expression; 47 private Location location; 48 49 public IfInterceptor(ExecutableElement next, ScriptingElement scr) { 50 super(next); 51 expression = Expression.compile(scr.getIf()); 52 location = scr.getLocation(); 53 } 54 55 public void execute(final DynamicContext ctx) { 56 boolean ok = false; 57 58 try { 59 final Object res = expression.evaluate(ctx); 60 61 if (res != null) { 62 if (res instanceof Boolean ) { 63 ok = (Boolean ) res; 64 } else if (trueStrs.contains(String.valueOf(res))) { 65 ok = true; 66 } 67 } 68 } catch (Expression.EvaluationException e) { 69 LOG.log(Level.WARNING, 70 "Unable to evaluate if condition \"" + 71 expression.getExpression() + "\" for script " + location + 72 ": " + e.getMessage(), e); 73 } 74 75 if (ok) { executeNext(ctx); 77 } else { 78 if (LOG.isLoggable(Level.FINE)) { 79 LOG.fine("if=\""+expression.getExpression()+"\" is false, element body is skipped."); 80 } 81 } 82 } 83 84 public static ExecutableElement prepare( 85 final ExecutableElement next, final ScriptingElement s) { 86 final String ifExpr = s.getIf(); 87 88 if ((ifExpr == null) || (ifExpr.length() == 0)) { 89 return next; 90 } 91 92 return new IfInterceptor(next, s); 93 } 94 } 95 | Popular Tags |