BeanDeserializer.java 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
  3. *
  4. * The Apache Software License, Version 1.1
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in
  15. * the documentation and/or other materials provided with the
  16. * distribution.
  17. *
  18. * 3. The end-user documentation included with the redistribution, if
  19. * any, must include the following acknowlegement:
  20. * "This product includes software developed by the
  21. * Caucho Technology (http://www.caucho.com/)."
  22. * Alternately, this acknowlegement may appear in the software itself,
  23. * if and wherever such third-party acknowlegements normally appear.
  24. *
  25. * 4. The names "Burlap", "Resin", and "Caucho" must not be used to
  26. * endorse or promote products derived from this software without prior
  27. * written permission. For written permission, please contact
  28. * info@caucho.com.
  29. *
  30. * 5. Products derived from this software may not be called "Resin"
  31. * nor may "Resin" appear in their names without prior written
  32. * permission of Caucho Technology.
  33. *
  34. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  35. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  36. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  37. * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
  38. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  39. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  40. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  41. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  42. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  43. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  44. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. *
  46. * @author Scott Ferguson
  47. */
  48. package com.hmsoft.remote.caucho.hessian.io;
  49. import java.io.IOException;
  50. import java.lang.reflect.Constructor;
  51. import java.lang.reflect.Method;
  52. import java.lang.reflect.Modifier;
  53. import java.util.HashMap;
  54. /**
  55. * Serializing an object for known object types.
  56. */
  57. public class BeanDeserializer extends AbstractMapDeserializer {
  58. private Class _type;
  59. private HashMap _methodMap;
  60. private Method _readResolve;
  61. private Constructor _constructor;
  62. private Object []_constructorArgs;
  63. public BeanDeserializer(Class cl)
  64. {
  65. _type = cl;
  66. _methodMap = getMethodMap(cl);
  67. _readResolve = getReadResolve(cl);
  68. Constructor []constructors = cl.getConstructors();
  69. int bestLength = Integer.MAX_VALUE;
  70. for (int i = 0; i < constructors.length; i++) {
  71. if (constructors[i].getParameterTypes().length < bestLength) {
  72. _constructor = constructors[i];
  73. bestLength = _constructor.getParameterTypes().length;
  74. }
  75. }
  76. if (_constructor != null) {
  77. _constructor.setAccessible(true);
  78. Class []params = _constructor.getParameterTypes();
  79. _constructorArgs = new Object[params.length];
  80. for (int i = 0; i < params.length; i++) {
  81. _constructorArgs[i] = getParamArg(params[i]);
  82. }
  83. }
  84. }
  85. public Class getType()
  86. {
  87. return _type;
  88. }
  89. public Object readMap(AbstractHessianInput in)
  90. throws IOException
  91. {
  92. try {
  93. Object obj = instantiate();
  94. return readMap(in, obj);
  95. } catch (IOException e) {
  96. throw e;
  97. } catch (Exception e) {
  98. throw new IOExceptionWrapper(e);
  99. }
  100. }
  101. public Object readMap(AbstractHessianInput in, Object obj)
  102. throws IOException
  103. {
  104. try {
  105. int ref = in.addRef(obj);
  106. while (! in.isEnd()) {
  107. Object key = in.readObject();
  108. Method method = (Method) _methodMap.get(key);
  109. if (method != null) {
  110. Object value = in.readObject(method.getParameterTypes()[0]);
  111. method.invoke(obj, new Object[] {value });
  112. }
  113. else {
  114. Object value = in.readObject();
  115. }
  116. }
  117. in.readMapEnd();
  118. Object resolve = resolve(obj);
  119. if (obj != resolve)
  120. in.setRef(ref, resolve);
  121. return resolve;
  122. } catch (IOException e) {
  123. throw e;
  124. } catch (Exception e) {
  125. throw new IOExceptionWrapper(e);
  126. }
  127. }
  128. private Object resolve(Object obj)
  129. {
  130. // if there's a readResolve method, call it
  131. try {
  132. if (_readResolve != null)
  133. return _readResolve.invoke(obj, new Object[0]);
  134. } catch (Exception e) {
  135. }
  136. return obj;
  137. }
  138. protected Object instantiate()
  139. throws Exception
  140. {
  141. return _constructor.newInstance(_constructorArgs);
  142. }
  143. /**
  144. * Returns the readResolve method
  145. */
  146. protected Method getReadResolve(Class cl)
  147. {
  148. for (; cl != null; cl = cl.getSuperclass()) {
  149. Method []methods = cl.getDeclaredMethods();
  150. for (int i = 0; i < methods.length; i++) {
  151. Method method = methods[i];
  152. if (method.getName().equals("readResolve") &&
  153. method.getParameterTypes().length == 0)
  154. return method;
  155. }
  156. }
  157. return null;
  158. }
  159. /**
  160. * Creates a map of the classes fields.
  161. */
  162. protected HashMap getMethodMap(Class cl)
  163. {
  164. HashMap methodMap = new HashMap();
  165. for (; cl != null; cl = cl.getSuperclass()) {
  166. Method []methods = cl.getDeclaredMethods();
  167. for (int i = 0; i < methods.length; i++) {
  168. Method method = methods[i];
  169. if (Modifier.isStatic(method.getModifiers()))
  170. continue;
  171. String name = method.getName();
  172. if (! name.startsWith("set"))
  173. continue;
  174. Class []paramTypes = method.getParameterTypes();
  175. if (paramTypes.length != 1)
  176. continue;
  177. if (! method.getReturnType().equals(void.class))
  178. continue;
  179. if (findGetter(methods, name, paramTypes[0]) == null)
  180. continue;
  181. // XXX: could parameterize the handler to only deal with public
  182. try {
  183. method.setAccessible(true);
  184. } catch (Throwable e) {
  185. e.printStackTrace();
  186. }
  187. name = name.substring(3);
  188. int j = 0;
  189. for (; j < name.length() && Character.isUpperCase(name.charAt(j)); j++) {
  190. }
  191. if (j == 1)
  192. name = name.substring(0, j).toLowerCase() + name.substring(j);
  193. else if (j > 1)
  194. name = name.substring(0, j - 1).toLowerCase() + name.substring(j - 1);
  195. methodMap.put(name, method);
  196. }
  197. }
  198. return methodMap;
  199. }
  200. /**
  201. * Finds any matching setter.
  202. */
  203. private Method findGetter(Method []methods, String setterName, Class arg)
  204. {
  205. String getterName = "get" + setterName.substring(3);
  206. for (int i = 0; i < methods.length; i++) {
  207. Method method = methods[i];
  208. if (! method.getName().equals(getterName))
  209. continue;
  210. if (! method.getReturnType().equals(arg))
  211. continue;
  212. Class []params = method.getParameterTypes();
  213. if (params.length == 0)
  214. return method;
  215. }
  216. return null;
  217. }
  218. /**
  219. * Creates a map of the classes fields.
  220. */
  221. protected static Object getParamArg(Class cl)
  222. {
  223. if (! cl.isPrimitive())
  224. return null;
  225. else if (boolean.class.equals(cl))
  226. return Boolean.FALSE;
  227. else if (byte.class.equals(cl))
  228. return Byte.valueOf((byte) 0);
  229. else if (short.class.equals(cl))
  230. return Short.valueOf((short) 0);
  231. else if (char.class.equals(cl))
  232. return Character.valueOf((char) 0);
  233. else if (int.class.equals(cl))
  234. return Integer.valueOf(0);
  235. else if (long.class.equals(cl))
  236. return Long.valueOf(0);
  237. else if (float.class.equals(cl))
  238. return Double.valueOf(0);
  239. else if (double.class.equals(cl))
  240. return Double.valueOf(0);
  241. else
  242. throw new UnsupportedOperationException();
  243. }
  244. }