1 package org.apache.velocity.runtime.parser.node;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.velocity.context.InternalContextAdapter;
23 import org.apache.velocity.exception.MathException;
24 import org.apache.velocity.exception.MethodInvocationException;
25 import org.apache.velocity.exception.TemplateInitException;
26 import org.apache.velocity.runtime.RuntimeConstants;
27 import org.apache.velocity.runtime.parser.Parser;
28 import org.apache.velocity.util.TemplateNumber;
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 public abstract class ASTMathNode extends SimpleNode
44 {
45 protected boolean strictMode = false;
46
47 public ASTMathNode(int id)
48 {
49 super(id);
50 }
51
52 public ASTMathNode(Parser p, int id)
53 {
54 super(p, id);
55 }
56
57
58
59
60 public Object init(InternalContextAdapter context, Object data) throws TemplateInitException
61 {
62 super.init(context, data);
63 strictMode = rsvc.getBoolean(RuntimeConstants.STRICT_MATH, false);
64 return data;
65 }
66
67
68
69
70 public Object jjtAccept(ParserVisitor visitor, Object data)
71 {
72 return visitor.visit(this, data);
73 }
74
75
76
77
78
79
80
81
82 public Object value(InternalContextAdapter context) throws MethodInvocationException
83 {
84 Object left = jjtGetChild(0).value(context);
85 Object right = jjtGetChild(1).value(context);
86
87
88
89
90 Object special = handleSpecial(left, right, context);
91 if (special != null)
92 {
93 return special;
94 }
95
96
97
98
99 if (left instanceof TemplateNumber)
100 {
101 left = ((TemplateNumber)left).getAsNumber();
102 }
103 if (right instanceof TemplateNumber)
104 {
105 right = ((TemplateNumber)right).getAsNumber();
106 }
107
108
109
110
111 if (!(left instanceof Number) || !(right instanceof Number))
112 {
113 boolean wrongright = (left instanceof Number);
114 boolean wrongtype = wrongright ? right != null : left != null;
115 String msg = (wrongright ? "Right" : "Left")
116 + " side of math operation ("
117 + jjtGetChild(wrongright ? 1 : 0).literal() + ") "
118 + (wrongtype ? "is not a Number. " : "has a null value. ")
119 + getLocation(context);
120 if (strictMode)
121 {
122 log.error(msg);
123 throw new MathException(msg);
124 }
125 else
126 {
127 log.debug(msg);
128 return null;
129 }
130 }
131
132 return perform((Number)left, (Number)right, context);
133 }
134
135
136
137
138
139
140
141 protected Object handleSpecial(Object left, Object right, InternalContextAdapter context)
142 {
143
144 return null;
145 }
146
147
148
149
150 public abstract Number perform(Number left, Number right, InternalContextAdapter context);
151
152 }
153
154
155
156