KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freemarker > template > SimpleHash


1 /*
2  * Copyright (c) 2003 The Visigoth Software Society. All rights
3  * reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in
14  * the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowledgement:
19  * "This product includes software developed by the
20  * Visigoth Software Society (http://www.visigoths.org/)."
21  * Alternately, this acknowledgement may appear in the software itself,
22  * if and wherever such third-party acknowledgements normally appear.
23  *
24  * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
25  * project contributors may be used to endorse or promote products derived
26  * from this software without prior written permission. For written
27  * permission, please contact visigoths@visigoths.org.
28  *
29  * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
30  * nor may "FreeMarker" or "Visigoth" appear in their names
31  * without prior written permission of the Visigoth Software Society.
32  *
33  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
34  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36  * DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR
37  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
40  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
41  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
42  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
43  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  * ====================================================================
46  *
47  * This software consists of voluntary contributions made by many
48  * individuals on behalf of the Visigoth Software Society. For more
49  * information on the Visigoth Software Society, please see
50  * http://www.visigoths.org/
51  */

52
53 package freemarker.template;
54
55 import java.util.*;
56 import java.io.Serializable JavaDoc;
57
58 /**
59  * <p>A simple implementation of the <tt>TemplateHashModelEx</tt>
60  * interface, using an underlying {@link Map} or {@link SortedMap}.</p>
61  *
62  * <p>This class is thread-safe if you don't call the <tt>put</tt> or <tt>remove</tt> methods
63  * after you have made the object available for multiple threads.
64  *
65  * <p><b>Note:</b><br />
66  * As of 2.0, this class is unsynchronized by default.
67  * To obtain a synchronized wrapper, call the {@link #synchronizedWrapper} method.</p>
68  *
69  * @version $Id: SimpleHash.java,v 1.63 2004/01/06 17:06:43 szegedia Exp $
70  * @see SimpleSequence
71  * @see SimpleScalar
72  */

73 public class SimpleHash extends WrappingTemplateModel
74 implements TemplateHashModelEx, Serializable JavaDoc {
75
76     private Map map;
77     private boolean putFailed;
78
79     /**
80      * Constructs an empty hash that uses the default wrapper set in
81      * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)}.
82      */

83     public SimpleHash() {
84         this((ObjectWrapper)null);
85     }
86
87     /**
88      * Creates a new simple hash with the copy of the underlying map and the
89      * default wrapper set in
90      * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)}.
91      * @param map The Map to use for the key/value pairs. It makes a copy for
92      * internal use. If the map implements the {@link SortedMap} interface, the
93      * internal copy will be a {@link TreeMap}, otherwise it will be a
94      * {@link HashMap}.
95      */

96     public SimpleHash(Map map) {
97         this(map, null);
98     }
99
100     /**
101      * Creates an empty simple hash using the specified object wrapper.
102      * @param wrapper The object wrapper to use to wrap objects into
103      * {@link TemplateModel} instances. If null, the default wrapper set in
104      * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)} is
105      * used.
106      */

107     public SimpleHash(ObjectWrapper wrapper) {
108         super(wrapper);
109         map = new HashMap();
110     }
111
112     /**
113      * Creates a new simple hash with the copy of the underlying map and
114      * either the default wrapper set in
115      * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)}, or
116      * the {@link freemarker.ext.beans.BeansWrapper JavaBeans wrapper}.
117      * @param map The Map to use for the key/value pairs. It makes a copy for
118      * internal use. If the map implements the {@link SortedMap} interface, the
119      * internal copy will be a {@link TreeMap}, otherwise it will be a
120      * @param wrapper The object wrapper to use to wrap objects into
121      * {@link TemplateModel} instances. If null, the default wrapper set in
122      * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)} is
123      * used.
124      */

125     public SimpleHash(Map map, ObjectWrapper wrapper) {
126         super(wrapper);
127         try {
128             this.map = copyMap(map);
129         } catch (ConcurrentModificationException cme) {
130             //This will occur extremely rarely.
131
//If it does, we just wait 5 ms and try again. If
132
// the ConcurrentModificationException
133
// is thrown again, we just let it bubble up this time.
134
// TODO: Maybe we should log here.
135
try {
136                 Thread.sleep(5);
137             } catch (InterruptedException JavaDoc ie) {
138             }
139             synchronized (map) {
140                 this.map = copyMap(map);
141             }
142         }
143     }
144
145     protected Map copyMap(Map map) {
146         if (map instanceof HashMap) {
147             return (Map) ((HashMap) map).clone();
148         }
149         if (map instanceof SortedMap) {
150             if (map instanceof TreeMap) {
151                 return (Map) ((TreeMap) map).clone();
152             }
153             else {
154                 return new TreeMap((SortedMap) map);
155             }
156         }
157         return new HashMap(map);
158     }
159
160     /**
161      * Adds a key-value entry to the map.
162      *
163      * @param key the name by which the object is
164      * identified in the template.
165      * @param obj the object to store.
166      */

167     public void put(String JavaDoc key, Object JavaDoc obj) {
168         map.put(key, obj);
169     }
170
171     /**
172      * Puts a boolean in the map
173      *
174      * @param key the name by which the resulting <tt>TemplateModel</tt>
175      * is identified in the template.
176      * @param b the boolean to store.
177      */

178     public void put(String JavaDoc key, boolean b) {
179         put(key, b ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE);
180     }
181
182     public TemplateModel get(String JavaDoc key) throws TemplateModelException {
183         Object JavaDoc result = map.get(key);
184         if (result instanceof TemplateModel) {
185             return (TemplateModel) result;
186         }
187         TemplateModel tm = wrap(result);
188         if (!putFailed) try {
189             map.put(key, tm);
190         } catch (Exception JavaDoc e) {
191             // If it's immutable or something, we just keep going.
192
putFailed = true;
193         }
194         return tm;
195     }
196
197
198     /**
199      * Removes the given key from the underlying map.
200      *
201      * @param key the key to be removed
202      */

203     public void remove(String JavaDoc key) {
204         map.remove(key);
205     }
206
207     /**
208      * Adds all the key/value entries in the map
209      * @param m the map with the entries to add, the keys are assumed to be strings.
210      */

211
212     public void putAll(Map m) {
213         for (Iterator it = m.entrySet().iterator(); it.hasNext();) {
214             Map.Entry entry = (Map.Entry) it.next();
215             this.put((String JavaDoc) entry.getKey(), entry.getValue());
216         }
217     }
218
219     /**
220      * Convenience method for returning the <tt>String</tt> value of the
221      * underlying map.
222      */

223     public String JavaDoc toString() {
224         return map.toString();
225     }
226
227     public int size() {
228         return map.size();
229     }
230
231     public boolean isEmpty() {
232         return map == null || map.isEmpty();
233     }
234
235     public TemplateCollectionModel keys() {
236         return new SimpleCollection(map.keySet(), getObjectWrapper());
237     }
238
239     public TemplateCollectionModel values() {
240         return new SimpleCollection(map.values(), getObjectWrapper());
241     }
242
243     public SimpleHash synchronizedWrapper() {
244         return new SynchronizedHash();
245     }
246     
247     
248     private class SynchronizedHash extends SimpleHash {
249
250         public synchronized boolean isEmpty() {
251             return SimpleHash.this.isEmpty();
252         }
253         
254         public synchronized void put(String JavaDoc key, Object JavaDoc obj) {
255             SimpleHash.this.put(key, obj);
256         }
257
258         public synchronized TemplateModel get(String JavaDoc key) throws TemplateModelException {
259             return SimpleHash.this.get(key);
260         }
261
262         public synchronized void remove(String JavaDoc key) {
263             SimpleHash.this.remove(key);
264         }
265
266         public synchronized int size() {
267             return SimpleHash.this.size();
268         }
269
270         public synchronized TemplateCollectionModel keys() {
271             return SimpleHash.this.keys();
272         }
273
274         public synchronized TemplateCollectionModel values() {
275             return SimpleHash.this.values();
276         }
277     }
278 }
279
Popular Tags