View Javadoc

1   /*
2    * Copyright  2004-2005 Stefan Reuter
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *
16   */
17  package net.sf.asterisk.manager.impl;
18  
19  import java.lang.reflect.InvocationTargetException;
20  import java.lang.reflect.Method;
21  import java.util.HashMap;
22  import java.util.Iterator;
23  import java.util.Map;
24  
25  import net.sf.asterisk.AsteriskVersion;
26  import net.sf.asterisk.manager.ActionBuilder;
27  import net.sf.asterisk.manager.action.ManagerAction;
28  
29  import net.sf.asterisk.util.Log;
30  import net.sf.asterisk.util.LogFactory;
31  
32  /***
33   * Default implementation of the ActionBuilder interface.
34   * 
35   * @author srt
36   * @version $Id: ActionBuilderImpl.java,v 1.5 2005/11/08 15:25:18 srt Exp $
37   */
38  public class ActionBuilderImpl implements ActionBuilder
39  {
40      private static final String LINE_SEPARATOR = "\r\n";
41  
42      /***
43       * Instance logger.
44       */
45      private final Log logger = LogFactory.getLog(getClass());
46      private AsteriskVersion targetVersion;
47  
48      /***
49       * Creates a new ActionBuilder for Asterisk 1.0.
50       */
51      public ActionBuilderImpl()
52      {
53          this.targetVersion = AsteriskVersion.ASTERISK_1_0;
54      }
55  
56      public void setTargetVersion(AsteriskVersion targetVersion)
57      {
58          this.targetVersion = targetVersion;
59      }
60  
61      public String buildAction(final ManagerAction action)
62      {
63          return buildAction(action, null);
64      }
65  
66      public String buildAction(final ManagerAction action, final String internalActionId)
67      {
68          StringBuffer sb;
69          Map getters;
70  
71          sb = new StringBuffer("action: ");
72          sb.append(action.getAction());
73          sb.append(LINE_SEPARATOR);
74          if (internalActionId != null)
75          {
76              sb.append("actionid: ");
77              sb.append(Util.addInternalActionId(action.getActionId(), internalActionId));
78              sb.append(LINE_SEPARATOR);
79          }
80          else if (action.getActionId() != null)
81          {
82              sb.append("actionid: ");
83              sb.append(action.getActionId());
84              sb.append(LINE_SEPARATOR);
85          }
86          
87          getters = getGetters(action.getClass());
88  
89          Iterator i = getters.keySet().iterator();
90          while (i.hasNext())
91          {
92              String name;
93              Method getter;
94              Object value;
95  
96              name = (String) i.next();
97  
98              if ("class".equals(name) || "action".equals(name) || "actionid".equals(name))
99              {
100                 continue;
101             }
102 
103             getter = (Method) getters.get(name);
104             try
105             {
106                 value = getter.invoke(action, new Object[]{});
107             }
108             catch (IllegalAccessException ex)
109             {
110                 logger.error("Unable to retrieve property '" + name + "' of "
111                         + action.getClass(), ex);
112                 continue;
113             }
114             catch (InvocationTargetException ex)
115             {
116                 logger.error("Unable to retrieve property '" + name + "' of "
117                         + action.getClass(), ex);
118                 continue;
119             }
120 
121             if (value == null)
122             {
123                 continue;
124             }
125             else if (value instanceof Class)
126             {
127                 continue;
128             }
129             else if (value instanceof Map)
130             {
131                 appendMap(sb, name, (Map) value);
132             }
133             else if (value instanceof String)
134             {
135                 appendString(sb, name, (String) value);
136             }
137             else
138             {
139                 appendString(sb, name, value.toString());
140             }
141         }
142 
143         sb.append(LINE_SEPARATOR);
144         return sb.toString();
145     }
146 
147     /***
148      * Returns a Map of getter methods of the given class.<br>
149      * The key of the map contains the name of the attribute that can be
150      * accessed by the getter, the value the getter itself (an instance of
151      * java.lang.reflect.Method). A method is considered a getter if its name
152      * starts with "get", it is declared public and takes no arguments.
153      * 
154      * @param clazz the class to return the getters for
155      * @return a Map of attributes and their accessor methods (getters)
156      */
157     private Map getGetters(final Class clazz)
158     {
159         Map accessors = new HashMap();
160         Method[] methods = clazz.getMethods();
161 
162         for (int i = 0; i < methods.length; i++)
163         {
164             String name;
165             String methodName;
166             Method method = methods[i];
167 
168             methodName = method.getName();
169             if (!methodName.startsWith("get"))
170             {
171                 continue;
172             }
173 
174             // skip methods with != 0 parameters
175             if (method.getParameterTypes().length != 0)
176             {
177                 continue;
178             }
179 
180             // ok seems to be an accessor
181             name = methodName.substring("get".length()).toLowerCase();
182 
183             if (name.length() == 0)
184             {
185                 continue;
186             }
187 
188             accessors.put(name, method);
189         }
190 
191         return accessors;
192     }
193 
194     protected void appendMap(StringBuffer sb, String key, Map values)
195     {
196         String singularKey;
197 
198         // strip plural s (i.e. use "variable: " instead of "variables: "
199         if (key.endsWith("s"))
200         {
201             singularKey = key.substring(0, key.length() - 1);
202         }
203         else
204         {
205             singularKey = key;
206         }
207 
208         if (targetVersion.isAtLeast(AsteriskVersion.ASTERISK_1_2))
209         {
210             appendMap12(sb, singularKey, values);
211         }
212         else
213         {
214             appendMap10(sb, singularKey, values);
215         }
216     }
217 
218     protected void appendMap10(StringBuffer sb, String singularKey, Map values)
219     {
220         Iterator entryIterator;
221 
222         sb.append(singularKey);
223         sb.append(": ");
224         entryIterator = values.entrySet().iterator();
225         while (entryIterator.hasNext())
226         {
227             Map.Entry entry;
228 
229             entry = (Map.Entry) entryIterator.next();
230             sb.append(entry.getKey());
231             sb.append("=");
232             if (entry.getValue() != null)
233             {
234                 sb.append(entry.getValue());
235             }
236 
237             if (entryIterator.hasNext())
238             {
239                 sb.append("|");
240             }
241         }
242         sb.append(LINE_SEPARATOR);
243     }
244 
245     protected void appendMap12(StringBuffer sb, String singularKey, Map values)
246     {
247         Iterator entryIterator;
248 
249         entryIterator = values.entrySet().iterator();
250         while (entryIterator.hasNext())
251         {
252             Map.Entry entry;
253 
254             entry = (Map.Entry) entryIterator.next();
255 
256             sb.append(singularKey);
257             sb.append(": ");
258             sb.append(entry.getKey());
259             sb.append("=");
260             if (entry.getValue() != null)
261             {
262                 sb.append(entry.getValue());
263             }
264 
265             sb.append(LINE_SEPARATOR);
266         }
267     }
268 
269     protected void appendString(StringBuffer sb, String key, String value)
270     {
271         sb.append(key);
272         sb.append(": ");
273         sb.append(value);
274         sb.append(LINE_SEPARATOR);
275     }
276 }