Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
ForeachToken |
|
| 3.0;3 |
1 | // Copyright 2004, 2005 The Apache Software Foundation | |
2 | // | |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); | |
4 | // you may not use this file except in compliance with the License. | |
5 | // You may obtain a copy of the License at | |
6 | // | |
7 | // http://www.apache.org/licenses/LICENSE-2.0 | |
8 | // | |
9 | // Unless required by applicable law or agreed to in writing, software | |
10 | // distributed under the License is distributed on an "AS IS" BASIS, | |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
12 | // See the License for the specific language governing permissions and | |
13 | // limitations under the License. | |
14 | ||
15 | package org.apache.tapestry.script; | |
16 | ||
17 | import java.util.Iterator; | |
18 | import java.util.Map; | |
19 | ||
20 | import org.apache.hivemind.Location; | |
21 | ||
22 | /** | |
23 | * A looping operator, modeled after the Foreach component. It takes as its | |
24 | * source as property and iterates through the values, updating a symbol on each | |
25 | * pass. | |
26 | * <p> | |
27 | * As of 3.0, the index attribute has been added to foreach to keep track of the | |
28 | * current index of the iterating collection. | |
29 | * </p> | |
30 | * | |
31 | * @author Howard Lewis Ship, Harish Krishnaswamy | |
32 | * @since 1.0.1 | |
33 | */ | |
34 | ||
35 | class ForeachToken extends AbstractToken | |
36 | { | |
37 | ||
38 | private String _key; | |
39 | ||
40 | private String _index; | |
41 | ||
42 | private String _expression; | |
43 | ||
44 | ForeachToken(String key, String index, String expression, Location location) | |
45 | { | |
46 | 0 | super(location); |
47 | ||
48 | 0 | _key = key; |
49 | 0 | _index = index; |
50 | 0 | _expression = expression; |
51 | 0 | } |
52 | ||
53 | public void write(StringBuffer buffer, ScriptSession session) | |
54 | { | |
55 | 0 | Iterator i = (Iterator) session.evaluate(_expression, Iterator.class); |
56 | ||
57 | 0 | if (i == null) return; |
58 | ||
59 | 0 | Map symbols = session.getSymbols(); |
60 | ||
61 | 0 | int index = 0; |
62 | ||
63 | 0 | while(i.hasNext()) |
64 | { | |
65 | 0 | Object newValue = i.next(); |
66 | ||
67 | 0 | symbols.put(_key, newValue); |
68 | ||
69 | 0 | if (_index != null) symbols.put(_index, String.valueOf(index)); |
70 | ||
71 | 0 | writeChildren(buffer, session); |
72 | ||
73 | 0 | index++; |
74 | 0 | } |
75 | ||
76 | // We leave the last value as a symbol; don't know if that's | |
77 | // good or bad. | |
78 | 0 | } |
79 | } |