aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTIntegerRange.java
blob: 5135ff9260181e0dde84712dc7a380110987329e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package org.apache.velocity.runtime.parser.node;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.parser.Parser;
import org.apache.velocity.util.DuckType;
import org.apache.velocity.util.StringUtils;

import java.util.AbstractList;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * handles the range 'operator'  [ n .. m ]
 *
 * Please look at the Parser.jjt file which is
 * what controls the generation of this class.
 *
 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
 */
public class ASTIntegerRange extends SimpleNode
{
    /**
     * @param id
     */
    public ASTIntegerRange(int id)
    {
        super(id);
    }

    /**
     * @param p
     * @param id
     */
    public ASTIntegerRange(Parser p, int id)
    {
        super(p, id);
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.SimpleNode#jjtAccept(org.apache.velocity.runtime.parser.node.ParserVisitor, java.lang.Object)
     */
    @Override
    public Object jjtAccept(ParserVisitor visitor, Object data)
    {
        return visitor.visit(this, data);
    }

    public static class IntegerRange extends AbstractList<Integer>
    {
        public class RangeIterator implements ListIterator<Integer>
        {
            private int value;

            public RangeIterator()
            {
                value = left - delta;
            }

            public RangeIterator(int startIndex)
            {
                value = left + (startIndex - 1) * delta;
            }

            @Override
            public Integer next()
            {
                value += delta;
                return value;
            }

            @Override
            public boolean hasPrevious()
            {
                return value != left - delta;
            }

            @Override
            public Integer previous()
            {
                value -= delta;
                return value;
            }

            @Override
            public int nextIndex()
            {
                return (value + delta - left) * delta;
            }

            @Override
            public int previousIndex()
            {
                return (value - delta - left) * delta;
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException("integer range is read only");
            }

            @Override
            public void set(Integer integer)
            {
                throw new UnsupportedOperationException("integer range is read only");
            }

            @Override
            public void add(Integer integer)
            {
                throw new UnsupportedOperationException("integer range is read only");
            }

            @Override
            public boolean hasNext()
            {
                return value != right;
            }
        }

        private int left;
        private int right;
        private int delta;

        public IntegerRange(int left, int right, int delta)
        {
            this.left = left;
            this.right = right;
            this.delta = delta;
        }

        @Override
        public Iterator<Integer> iterator()
        {
            return new RangeIterator();
        }

        @Override
        public Integer get(int index)
        {
            int ret = left + delta * index;
            if (delta > 0 && ret > right || delta < 0 && ret < right)
            {
                throw new IndexOutOfBoundsException();
            }
            return ret;
        }

        @Override
        public int indexOf(Object o)
        {
            int v = DuckType.asNumber(o).intValue();
            v -= left;
            v *= delta;
            return v >= 0 && v < size() ? v : -1;
        }

        @Override
        public int lastIndexOf(Object o)
        {
            return indexOf(o);
        }

        @Override
        public ListIterator<Integer> listIterator()
        {
            return new RangeIterator();
        }

        @Override
        public ListIterator<Integer> listIterator(int index)
        {
            return new RangeIterator(index);
        }

        @Override
        public int size()
        {
            return Math.abs(right - left) + 1;
        }
    }

    /**
     *  does the real work.  Creates an Vector of Integers with the
     *  right value range
     *
     *  @param context  app context used if Left or Right of .. is a ref
     *  @return Object array of Integers
     * @throws MethodInvocationException
     */
    @Override
    public Object value(InternalContextAdapter context)
        throws MethodInvocationException
    {
        /*
         *  get the two range ends
         */

        Object left = jjtGetChild(0).value( context );
        Object right = jjtGetChild(1).value( context );

        /*
         *  if either is null, lets log and bail
         */

        if (left == null || right == null)
        {
            log.error((left == null ? "Left" : "Right")
                           + " side of range operator [n..m] has null value."
                           + " Operation not possible. "
                           + StringUtils.formatFileString(this));
            return null;
        }

        /*
         *  if not a Number, try to convert
         */

        try
        {
            left = DuckType.asNumber(left);
        }
        catch (NumberFormatException nfe) {}

        try
        {
            right = DuckType.asNumber(right);
        }
        catch (NumberFormatException nfe) {}

        /*
         *  if still not a Number, nothing we can do
         */

        if ( !( left instanceof Number )  || !( right instanceof Number ))
        {
            log.error((!(left instanceof Number) ? "Left" : "Right")
                           + " side of range operator is not convertible to a Number. "
                           + StringUtils.formatFileString(this));
            return null;
        }

        /*
         *  get the two integer values of the ends of the range
         */

        int l = ((Number) left).intValue() ;
        int r = ((Number) right).intValue();

        /*
         *  Determine whether the increment is positive or negative.
         */

        int delta = ( l >= r ) ? -1 : 1;

        /*
         * Return the corresponding integer range
         */

        return new IntegerRange(l, r, delta);
    }

    /**
     * @throws TemplateInitException
     * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
     */
    @Override
    public Object init(InternalContextAdapter context, Object data) throws TemplateInitException
    {
    	Object obj = super.init(context, data);
    	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
    	return obj;
    }

}