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 687177 2008-08-19 22:00:32Z 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 Class [] interfaces = clazz.getInterfaces();
49 for (int i = 0 ; i < interfaces.length; i++)
50 {
51 if (interfaces[i].equals(Map.class))
52 {
53 try
54 {
55 if (property != null)
56 {
57 setMethod(Map.class.getMethod("put", new Class [] { Object.class, Object.class }));
58 }
59 }
60 /**
61 * pass through application level runtime exceptions
62 */
63 catch( RuntimeException e )
64 {
65 throw e;
66 }
67 catch(Exception e)
68 {
69 String msg = "Exception while looking for put('" + property + "') method";
70 log.error(msg, e);
71 throw new VelocityException(msg, e);
72 }
73 break;
74 }
75 }
76 }
77
78 public Object execute(final Object o, final Object arg)
79 {
80 return ((Map) o).put(property, arg);
81 }
82 }