Save This Page
Home » freemarker-2.3.13 » freemarker.template » [javadoc | source]
    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.io.Serializable;
   56   import java.util.ConcurrentModificationException;
   57   import java.util.HashMap;
   58   import java.util.Iterator;
   59   import java.util.Map;
   60   import java.util.SortedMap;
   61   import java.util.TreeMap;
   62   
   63   import freemarker.ext.beans.BeansWrapper;
   64   
   65   /**
   66    * <p>A simple implementation of the <tt>TemplateHashModelEx</tt>
   67    * interface, using an underlying {@link Map} or {@link SortedMap}.</p>
   68    *
   69    * <p>This class is thread-safe if you don't call the <tt>put</tt> or <tt>remove</tt> methods
   70    * after you have made the object available for multiple threads.
   71    *
   72    * <p><b>Note:</b><br />
   73    * As of 2.0, this class is unsynchronized by default.
   74    * To obtain a synchronized wrapper, call the {@link #synchronizedWrapper} method.</p>
   75    *
   76    * @version $Id: SimpleHash.java,v 1.72.2.2 2006/02/26 18:26:18 revusky Exp $
   77    * @see SimpleSequence
   78    * @see SimpleScalar
   79    */
   80   public class SimpleHash extends WrappingTemplateModel 
   81   implements TemplateHashModelEx, Serializable {
   82   
   83       private Map map;
   84       private boolean putFailed;
   85       private Map unwrappedMap;
   86   
   87       /**
   88        * Constructs an empty hash that uses the default wrapper set in
   89        * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)}.
   90        */
   91       public SimpleHash() {
   92           this((ObjectWrapper)null);
   93       }
   94   
   95       /**
   96        * Creates a new simple hash with the copy of the underlying map and the
   97        * default wrapper set in 
   98        * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)}.
   99        * @param map The Map to use for the key/value pairs. It makes a copy for 
  100        * internal use. If the map implements the {@link SortedMap} interface, the
  101        * internal copy will be a {@link TreeMap}, otherwise it will be a 
  102        * {@link HashMap}.
  103        */
  104       public SimpleHash(Map map) {
  105           this(map, null);
  106       }
  107   
  108       /**
  109        * Creates an empty simple hash using the specified object wrapper.
  110        * @param wrapper The object wrapper to use to wrap objects into
  111        * {@link TemplateModel} instances. If null, the default wrapper set in 
  112        * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)} is
  113        * used.
  114        */
  115       public SimpleHash(ObjectWrapper wrapper) {
  116           super(wrapper);
  117           map = new HashMap();
  118       }
  119   
  120       /**
  121        * Creates a new simple hash with the copy of the underlying map and 
  122        * either the default wrapper set in 
  123        * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)}, or
  124        * the {@link freemarker.ext.beans.BeansWrapper JavaBeans wrapper}.
  125        * @param map The Map to use for the key/value pairs. It makes a copy for 
  126        * internal use. If the map implements the {@link SortedMap} interface, the
  127        * internal copy will be a {@link TreeMap}, otherwise it will be a 
  128        * @param wrapper The object wrapper to use to wrap objects into
  129        * {@link TemplateModel} instances. If null, the default wrapper set in 
  130        * {@link WrappingTemplateModel#setDefaultObjectWrapper(ObjectWrapper)} is
  131        * used.
  132        */
  133       public SimpleHash(Map map, ObjectWrapper wrapper) {
  134           super(wrapper);
  135           try {
  136               this.map = copyMap(map);
  137           } catch (ConcurrentModificationException cme) {
  138               //This will occur extremely rarely.
  139               //If it does, we just wait 5 ms and try again. If 
  140               // the ConcurrentModificationException
  141               // is thrown again, we just let it bubble up this time.
  142               // TODO: Maybe we should log here.
  143               try {
  144                   Thread.sleep(5);
  145               } catch (InterruptedException ie) {
  146               }
  147               synchronized (map) {
  148                   this.map = copyMap(map);
  149               }
  150           }
  151       }
  152   
  153       protected Map copyMap(Map map) {
  154           if (map instanceof HashMap) {
  155               return (Map) ((HashMap) map).clone();
  156           }
  157           if (map instanceof SortedMap) {
  158               if (map instanceof TreeMap) {
  159                   return (Map) ((TreeMap) map).clone();
  160               }
  161               else {
  162                   return new TreeMap((SortedMap) map);
  163               }
  164           } 
  165           return new HashMap(map);
  166       }
  167   
  168       /**
  169        * Adds a key-value entry to the map.
  170        *
  171        * @param key the name by which the object is
  172        * identified in the template.
  173        * @param obj the object to store.
  174        */
  175       public void put(String key, Object obj) {
  176           map.put(key, obj);
  177           unwrappedMap = null;
  178       }
  179   
  180       /**
  181        * Puts a boolean in the map
  182        *
  183        * @param key the name by which the resulting <tt>TemplateModel</tt>
  184        * is identified in the template.
  185        * @param b the boolean to store.
  186        */
  187       public void put(String key, boolean b) {
  188           put(key, b ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE);
  189       }
  190   
  191       public TemplateModel get(String key) throws TemplateModelException {
  192           Object result = map.get(key);
  193           if (result == null && key.length() == 1) {
  194               // just check for Character key if this is a single-character string
  195               try {
  196                   result = map.get(new Character(key.charAt(0)));
  197               } catch (Exception e) {}
  198           }
  199           if (result instanceof TemplateModel) {
  200               return (TemplateModel) result;
  201           }
  202           TemplateModel tm = wrap(result);
  203           // result != null || map.containsKey(key) criteria is to get around
  204           // ConcurrentModificationException when the map is accessed in a loop,
  205           // see bug #1939742 in SourceForge tracker.
  206           if (!putFailed && (result != null || map.containsKey(key))) {
  207               try {
  208                   map.put(key, tm);
  209               } catch (Exception e) {
  210                   // If it's immutable or something, we just keep going.
  211                   putFailed = true;
  212               }
  213           }
  214           return tm;
  215       }
  216   
  217   
  218       /**
  219        * Removes the given key from the underlying map.
  220        *
  221        * @param key the key to be removed
  222        */
  223       public void remove(String key) {
  224           map.remove(key);
  225       }
  226   
  227       /**
  228        * Adds all the key/value entries in the map
  229        * @param m the map with the entries to add, the keys are assumed to be strings.
  230        */
  231   
  232       public void putAll(Map m) {
  233           for (Iterator it = m.entrySet().iterator(); it.hasNext();) {
  234               Map.Entry entry = (Map.Entry) it.next();
  235               this.put((String) entry.getKey(), entry.getValue());
  236           }
  237       }
  238       
  239       /**
  240        * Note that this method creates and returns a deep-copy of the underlying hash used
  241        * internally. This could be a gotcha for some people
  242        * at some point who want to alter something in the data model,
  243        * but we should maintain our immutability semantics (at least using default SimpleXXX wrappers) 
  244        * for the data model. It will recursively unwrap the stuff in the underlying container. 
  245        */
  246       public Map toMap() throws TemplateModelException {
  247           if (unwrappedMap == null) {
  248               Class mapClass = this.map.getClass();
  249               Map m = null;
  250               try {
  251                   m = (Map) mapClass.newInstance();
  252               } catch (Exception e) {
  253                   throw new TemplateModelException("Error instantiating map of type " + mapClass.getName() + "\n" + e.getMessage());
  254               }
  255               // Create a copy to maintain immutability semantics and
  256               // Do nested unwrapping of elements if necessary.
  257               BeansWrapper bw = BeansWrapper.getDefaultInstance();
  258               for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
  259                   Map.Entry entry = (Map.Entry) it.next();
  260                   Object key = entry.getKey();
  261                   Object value = entry.getValue();
  262                   if (value instanceof TemplateModel) {
  263                       value = bw.unwrap((TemplateModel) value);
  264                   }
  265                   m.put(key, value);
  266               }
  267               unwrappedMap=m;
  268           }
  269           return unwrappedMap;
  270       }
  271   
  272       /**
  273        * Convenience method for returning the <tt>String</tt> value of the
  274        * underlying map.
  275        */
  276       public String toString() {
  277           return map.toString();
  278       }
  279   
  280       public int size() {
  281           return map.size();
  282       }
  283   
  284       public boolean isEmpty() {
  285           return map == null || map.isEmpty();
  286       }
  287   
  288       public TemplateCollectionModel keys() {
  289           return new SimpleCollection(map.keySet(), getObjectWrapper());
  290       }
  291   
  292       public TemplateCollectionModel values() {
  293           return new SimpleCollection(map.values(), getObjectWrapper());
  294       }
  295   
  296       public SimpleHash synchronizedWrapper() {
  297           return new SynchronizedHash();
  298       }
  299       
  300       
  301       private class SynchronizedHash extends SimpleHash {
  302   
  303           public boolean isEmpty() {
  304               synchronized (SimpleHash.this) {
  305                   return SimpleHash.this.isEmpty();
  306               }
  307           }
  308           
  309           public void put(String key, Object obj) {
  310               synchronized (SimpleHash.this) {
  311                   SimpleHash.this.put(key, obj);
  312               }
  313           }
  314   
  315           public TemplateModel get(String key) throws TemplateModelException {
  316               synchronized (SimpleHash.this) {
  317                   return SimpleHash.this.get(key);
  318               }
  319           }
  320   
  321           public void remove(String key) {
  322               synchronized (SimpleHash.this) {
  323                   SimpleHash.this.remove(key);
  324               }
  325           }
  326   
  327           public int size() {
  328               synchronized (SimpleHash.this) {
  329                   return SimpleHash.this.size();
  330               }
  331           }
  332   
  333           public TemplateCollectionModel keys() {
  334               synchronized (SimpleHash.this) {
  335                   return SimpleHash.this.keys();
  336               }
  337           }
  338   
  339           public TemplateCollectionModel values() {
  340               synchronized (SimpleHash.this) {
  341                   return SimpleHash.this.values();
  342               }
  343           }
  344           
  345           public Map toMap() throws TemplateModelException {
  346               synchronized (SimpleHash.this) {
  347                   return SimpleHash.this.toMap();
  348               }
  349           }
  350       
  351       }
  352   }

Save This Page
Home » freemarker-2.3.13 » freemarker.template » [javadoc | source]