KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tapestry > script > ForeachToken


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 JavaDoc;
18 import java.util.Map JavaDoc;
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 JavaDoc _key;
37
38     private String JavaDoc _index;
39
40     private String JavaDoc _expression;
41
42     ForeachToken(String JavaDoc key, String JavaDoc index, String JavaDoc expression, Location location)
43     {
44         super(location);
45
46         _key = key;
47         _index = index;
48         _expression = expression;
49     }
50
51     public void write(StringBuffer JavaDoc buffer, ScriptSession session)
52     {
53         Iterator JavaDoc i = (Iterator JavaDoc) session.evaluate(_expression, Iterator JavaDoc.class);
54
55         if (i == null)
56             return;
57
58         Map JavaDoc symbols = session.getSymbols();
59
60         int index = 0;
61
62         while (i.hasNext())
63         {
64             Object JavaDoc newValue = i.next();
65
66             symbols.put(_key, newValue);
67
68             if (_index != null)
69                 symbols.put(_index, String.valueOf(index));
70
71             writeChildren(buffer, session);
72
73             index++;
74         }
75
76         // We leave the last value as a symbol; don't know if that's
77
// good or bad.
78
}
79 }
Popular Tags