View Javadoc

1   package org.apache.velocity.runtime.parser.node;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.    
20   */
21  
22  import java.util.Map;
23  import org.apache.velocity.exception.VelocityException;
24  import org.apache.velocity.runtime.log.Log;
25  
26  /**
27   * SetExecutor that is smart about Maps. If it detects one, it does not
28   * use Reflection but a cast to access the setter. 
29   *
30   * @author <a href="mailto:henning@apache.org">Henning P. Schmiedehausen</a>
31   * @version $Id: MapSetExecutor.java 799457 2009-07-30 22:10:27Z nbubna $
32   * @since 1.5
33   */
34  public class MapSetExecutor
35          extends SetExecutor 
36  {
37      private final String property;
38  
39      public MapSetExecutor(final Log log, final Class clazz, final String property)
40      {
41          this.log = log;
42          this.property = property;
43          discover(clazz);
44      }
45  
46      protected void discover (final Class clazz)
47      {
48          if (property != null && Map.class.isAssignableFrom(clazz))
49          {
50              try
51              {
52                  setMethod(Map.class.getMethod("put", new Class [] { Object.class, Object.class }));
53              }
54              /**
55               * pass through application level runtime exceptions
56               */
57              catch( RuntimeException e )
58              {
59                  throw e;
60              }
61              catch(Exception e)
62              {
63                  String msg = "Exception while looking for put('" + property + "') method";
64                  log.error(msg, e);
65                  throw new VelocityException(msg, e);
66              }
67          }
68      }
69  
70      public Object execute(final Object o, final Object arg)
71      {
72          return ((Map) o).put(property, arg);
73      } 
74  }