|
|||||||||||||||||||
Source file | Conditionals | Statements | Methods | TOTAL | |||||||||||||||
ForeachToken.java | 100% | 100% | 100% | 100% |
|
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 source as property and | |
24 | * iterates through the values, updating a symbol on each pass. | |
25 | * <p> | |
26 | * As of 3.0, the index attribute has been added to foreach to keep track of the current index of | |
27 | * the iterating collection. | |
28 | * </p> | |
29 | * | |
30 | * @author Howard Lewis Ship, Harish Krishnaswamy | |
31 | * @since 1.0.1 | |
32 | */ | |
33 | ||
34 | class ForeachToken extends AbstractToken | |
35 | { | |
36 | private String _key; | |
37 | ||
38 | private String _index; | |
39 | ||
40 | private String _expression; | |
41 | ||
42 | 6 | ForeachToken(String key, String index, String expression, Location location) |
43 | { | |
44 | 6 | super(location); |
45 | ||
46 | 6 | _key = key; |
47 | 6 | _index = index; |
48 | 6 | _expression = expression; |
49 | } | |
50 | ||
51 | 6 | public void write(StringBuffer buffer, ScriptSession session) |
52 | { | |
53 | 6 | Iterator i = (Iterator) session.evaluate(_expression, Iterator.class); |
54 | ||
55 | 6 | if (i == null) |
56 | 2 | return; |
57 | ||
58 | 4 | Map symbols = session.getSymbols(); |
59 | ||
60 | 4 | int index = 0; |
61 | ||
62 | 4 | while (i.hasNext()) |
63 | { | |
64 | 8 | Object newValue = i.next(); |
65 | ||
66 | 8 | symbols.put(_key, newValue); |
67 | ||
68 | 8 | if (_index != null) |
69 | 4 | symbols.put(_index, String.valueOf(index)); |
70 | ||
71 | 8 | writeChildren(buffer, session); |
72 | ||
73 | 8 | index++; |
74 | } | |
75 | ||
76 | // We leave the last value as a symbol; don't know if that's | |
77 | // good or bad. | |
78 | } | |
79 | } |
|