aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Foreach.java
blob: 991e097a2c43d36242041f9b55ab7d6e59e0e9d2 (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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package org.apache.velocity.runtime.directive;

/*
 * 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.TemplateInitException;
import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.parser.ParseException;
import org.apache.velocity.runtime.parser.Token;
import org.apache.velocity.runtime.parser.node.*;
import org.apache.velocity.util.StringUtils;
import org.apache.velocity.util.introspection.Info;

import java.io.Closeable;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Foreach directive used for moving through arrays,
 * or objects that provide an Iterator.
 *
 * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
 * @author Daniel Rall
 * @version $Id$
 */
public class Foreach extends Directive
{
    /**
     * Return name of this directive.
     * @return The name of this directive.
     */
    @Override
    public String getName()
    {
        return "foreach";
    }

    /**
     * Return type of this directive.
     * @return The type of this directive.
     */
    @Override
    public int getType()
    {
        return BLOCK;
    }

    /**
     * The maximum number of times we're allowed to loop.
     */
    private int maxNbrLoops;

    /**
     * Whether or not to throw an Exception if the iterator is null.
     */
    private boolean skipInvalidIterator;

    /**
     * The reference name used to access each
     * of the elements in the list object. It
     * is the $item in the following:
     *
     * #foreach ($item in $list)
     *
     * This can be used class wide because
     * it is immutable.
     */
    private String elementKey;

    /**
     *  immutable, so create in init
     */
    protected Info uberInfo;

    /**
     *  simple init - init the tree and get the elementKey from
     *  the AST
     * @param rs
     * @param context
     * @param node
     * @throws TemplateInitException
     */
    @Override
    public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
        throws TemplateInitException
    {
        super.init(rs, context, node);

        maxNbrLoops = rsvc.getInt(RuntimeConstants.MAX_NUMBER_LOOPS,
                                  Integer.MAX_VALUE);
        if (maxNbrLoops < 1)
        {
            maxNbrLoops = Integer.MAX_VALUE;
        }
        skipInvalidIterator =
            rsvc.getBoolean(RuntimeConstants.SKIP_INVALID_ITERATOR, true);

        if (rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false))
        {
          // If we are in strict mode then the default for skipInvalidItarator
          // is true.  However, if the property is explicitly set, then honor the setting.
          skipInvalidIterator = rsvc.getBoolean(RuntimeConstants.SKIP_INVALID_ITERATOR, false);
        }

        /*
         *  this is really the only thing we can do here as everything
         *  else is context sensitive
         */
        SimpleNode sn = (SimpleNode) node.jjtGetChild(0);

        if (sn instanceof ASTReference)
        {
            elementKey = ((ASTReference) sn).getRootString();
        }
        else
        {
            /*
             * the default, error-prone way which we'll remove
             */
        	elementKey = sn.getFirstTokenImage().substring(1);
        }

        /*
         * make an uberinfo - saves new's later on
         */

        uberInfo = new Info(this.getTemplateName(),
                getLine(),getColumn());
    }

    /**
     * Extension hook to allow subclasses to control whether loop vars
     * are set locally or not. So, those in favor of VELOCITY-285, can
     * make that happen easily by overriding this and having it use
     * context.localPut(k,v). See VELOCITY-630 for more on this.
     * @param context
     * @param key
     * @param value
     */
    protected void put(InternalContextAdapter context, String key, Object value)
    {
        context.put(key, value);
    }

    /**
     * Retrieve the contextual iterator.
     * @param iterable
     * @param node
     * @return iterator
     */
    protected Iterator getIterator(Object iterable, Node node)
    {
        Iterator i = null;
        /*
         * do our introspection to see what our collection is
         */
        if (iterable != null)
        {
            try
            {
                i = rsvc.getUberspect().getIterator(iterable, uberInfo);
            }
            /*
             * pass through application level runtime exceptions
             */
            catch (RuntimeException e)
            {
                throw e;
            }
            catch (Exception ee)
            {
                String msg = "Error getting iterator for #foreach parameter "
                    + node.literal() + " at " + StringUtils.formatFileString(node);
                log.error(msg, ee);
                throw new VelocityException(msg, ee, rsvc.getLogContext().getStackTrace());
            }

            if (i == null && !skipInvalidIterator)
            {
                String msg = "#foreach parameter " + node.literal() + " at "
                    + StringUtils.formatFileString(node) + " is of type " + iterable.getClass().getName()
                    + " and cannot be iterated by " + rsvc.getUberspect().getClass().getName();
                log.error(msg);
                throw new VelocityException(msg, null, rsvc.getLogContext().getStackTrace());
            }
        }
        return i;
    }

    /**
     *  renders the #foreach() block
     * @param context
     * @param writer
     * @param node
     * @return True if the directive rendered successfully.
     * @throws IOException
     */
    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node)
        throws IOException
    {
        // Get the block ast tree which is always the last child ...
        Node block = node.jjtGetChild(node.jjtGetNumChildren()-1);

        // ... except if there is an #else clause
        Node elseBlock = null;
        Node previous = node.jjtGetChild(node.jjtGetNumChildren()-2);
        if (previous instanceof ASTBlock)
        {
            elseBlock = block;
            block = previous;
        }

        Node iterableNode = node.jjtGetChild(2);
        Object iterable = iterableNode.value(context);
        Iterator i = getIterator(iterable, iterableNode);
        if (i == null || !i.hasNext())
        {
            if (elseBlock != null)
            {
                renderBlock(context, writer, elseBlock);
            }
            return false;
        }

        /*
         * save the element key if there is one
         */
        Object o = context.get(elementKey);

        /*
         * roll our own scope class instead of using preRender(ctx)'s
         */
        ForeachScope foreach = null;
        if (isScopeProvided())
        {
            String name = getScopeName();
            foreach = new ForeachScope(this, context.get(name));
            context.put(name, foreach);
        }

        int count = 1;
        while (count <= maxNbrLoops && i.hasNext())
        {
            count++;

            put(context, elementKey, i.next());
            if (isScopeProvided())
            {
                // update the scope control
                foreach.index++;
                foreach.hasNext = i.hasNext();
            }

            try
            {
                renderBlock(context, writer, block);
            }
            catch (StopCommand stop)
            {
                if (stop.isFor(this))
                {
                    break;
                }
                else
                {
                    // clean up first
                    clean(context, o);
                    throw stop;
                }
            }
        }
        clean(context, o);
        /*
         * closes the iterator if it implements the Closeable interface
         */
        if (i instanceof Closeable && i != iterable) /* except if the iterable is the iterator itself */
        {
            ((Closeable)i).close();
        }
        return true;
    }

    protected void renderBlock(InternalContextAdapter context, Writer writer, Node block)
        throws IOException
    {
        block.render(context, writer);
    }

    protected void clean(InternalContextAdapter context, Object o)
    {
        /*
         *  restores element key if exists
         *  otherwise just removes
         */
        if (o != null)
        {
            context.put(elementKey, o);
        }
        else
        {
            context.remove(elementKey);
        }

        // clean up after the ForeachScope
        postRender(context);
    }

    /**
     * We do not allow a word token in any other arg position except for the 2nd since
     * we are looking for the pattern #foreach($foo in $bar).
     */
    @Override
    public void checkArgs(ArrayList<Integer> argtypes, Token t, String templateName)
      throws ParseException
    {
        if (argtypes.size() < 3)
        {
            throw new MacroParseException("Too few arguments to the #foreach directive",
              templateName, t);
        }
        else if (argtypes.get(0) != ParserTreeConstants.JJTREFERENCE)
        {
            throw new MacroParseException("Expected argument 1 of #foreach to be a reference",
                templateName, t);
        }
        else if (argtypes.get(1) != ParserTreeConstants.JJTWORD)
        {
            throw new MacroParseException("Expected word 'in' at argument position 2 in #foreach",
                templateName, t);
        }
        else if (argtypes.get(2) == ParserTreeConstants.JJTWORD)
        {
            throw new MacroParseException("Argument 3 of #foreach is of the wrong type",
                templateName, t);
        }
    }
}