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 java.util.ArrayList;
23 import java.util.List;
24
25 import org.apache.velocity.context.InternalContextAdapter;
26 import org.apache.velocity.exception.MethodInvocationException;
27 import org.apache.velocity.runtime.log.Log;
28 import org.apache.velocity.runtime.parser.Parser;
29
30
31
32
33
34
35
36
37
38 public class ASTIntegerRange extends SimpleNode
39 {
40
41
42
43 public ASTIntegerRange(int id)
44 {
45 super(id);
46 }
47
48
49
50
51
52 public ASTIntegerRange(Parser p, int id)
53 {
54 super(p, id);
55 }
56
57
58
59
60 public Object jjtAccept(ParserVisitor visitor, Object data)
61 {
62 return visitor.visit(this, data);
63 }
64
65
66
67
68
69
70
71
72
73 public Object value( InternalContextAdapter context)
74 throws MethodInvocationException
75 {
76
77
78
79
80 Object left = jjtGetChild(0).value( context );
81 Object right = jjtGetChild(1).value( context );
82
83
84
85
86
87 if (left == null || right == null)
88 {
89 log.error((left == null ? "Left" : "Right")
90 + " side of range operator [n..m] has null value."
91 + " Operation not possible. "
92 + Log.formatFileString(this));
93 return null;
94 }
95
96
97
98
99
100 if ( !( left instanceof Number ) || !( right instanceof Number ))
101 {
102 log.error((!(left instanceof Number) ? "Left" : "Right")
103 + " side of range operator is not a valid type. "
104 + "Currently only integers (1,2,3...) and the Number type are supported. "
105 + Log.formatFileString(this));
106 return null;
107 }
108
109
110
111
112
113
114 int l = ((Number) left).intValue() ;
115 int r = ((Number) right).intValue();
116
117
118
119
120
121 int nbrElements = Math.abs( l - r );
122 nbrElements += 1;
123
124
125
126
127
128 int delta = ( l >= r ) ? -1 : 1;
129
130
131
132
133
134 List elements = new ArrayList(nbrElements);
135 int value = l;
136
137 for (int i = 0; i < nbrElements; i++)
138 {
139
140 elements.add(new Integer(value));
141 value += delta;
142 }
143
144 return elements;
145 }
146 }