1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.el;
19 import java.lang.reflect.Method;
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import javax.servlet.jsp.el.ELException;
24 import javax.servlet.jsp.el.Expression;
25 import javax.servlet.jsp.el.ExpressionEvaluator;
26 import javax.servlet.jsp.el.FunctionMapper;
27 import javax.servlet.jsp.el.VariableResolver;
28
29 import org.apache.commons.el.ExpressionEvaluatorImpl;
30
31 import junit.framework.TestCase;
32
33
34
35
36
37 public class FunctionBindingTest extends TestCase {
38 public static String before() {return "before";}
39 public static String after() {return "after";}
40 public static String echo(final String s) {return s;}
41 private static class UpdatableFunctionMapper implements FunctionMapper {
42 private Map mappings = new HashMap();
43 public void setMapping(
44 final String name,
45 final Method function)
46 {
47 mappings.put(name,function);
48 }
49 public Method resolveFunction(
50 final String prefix,
51 final String localName)
52 {
53 return (Method)mappings.get(localName);
54 }
55 }
56
57 public void testFunctionBinding() throws ELException, NoSuchMethodException{
58 final String theExpression = "${theFunction()}";
59 final String nestedExpression = "${echo(theFunction())}";
60 final VariableResolver emptyVariableResolver = new VariableResolver() {
61 public Object resolveVariable(String arg0) throws ELException {
62 return null;
63 }
64 };
65 final UpdatableFunctionMapper fm = new UpdatableFunctionMapper();
66 final Method before = FunctionBindingTest.class.getDeclaredMethod("before",new Class[0]);
67 final Method after = FunctionBindingTest.class.getDeclaredMethod("after",new Class[0]);
68 final Method echo = FunctionBindingTest.class.getDeclaredMethod("echo", new Class[]{String.class});
69 final ExpressionEvaluator evaluator = new ExpressionEvaluatorImpl();
70 fm.setMapping("theFunction",before);
71 fm.setMapping("echo", echo);
72
73 final Expression expr = evaluator.parseExpression(theExpression, String.class, fm);
74 final Expression nestedExpr = evaluator.parseExpression(nestedExpression, String.class, fm);
75 assertEquals(
76 "before",
77 expr.evaluate(emptyVariableResolver));
78 assertEquals(
79 "before",
80 nestedExpr.evaluate(emptyVariableResolver));
81
82 fm.setMapping("theFunction",after);
83 assertEquals(
84 "after",
85 evaluator.evaluate(theExpression, String.class, emptyVariableResolver, fm));
86 assertEquals(
87 "before",
88 expr.evaluate(emptyVariableResolver));
89 assertEquals(
90 "after",
91 evaluator.evaluate(nestedExpression, String.class, emptyVariableResolver, fm));
92 assertEquals(
93 "before",
94 nestedExpr.evaluate(emptyVariableResolver));
95 }
96 }