Encoder.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /* Encoder.java
  2. Copyright (C) 2005, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.beans;
  32. import gnu.java.beans.DefaultExceptionListener;
  33. import gnu.java.beans.encoder.ArrayPersistenceDelegate;
  34. import gnu.java.beans.encoder.ClassPersistenceDelegate;
  35. import gnu.java.beans.encoder.CollectionPersistenceDelegate;
  36. import gnu.java.beans.encoder.MapPersistenceDelegate;
  37. import gnu.java.beans.encoder.PrimitivePersistenceDelegate;
  38. import java.util.AbstractCollection;
  39. import java.util.HashMap;
  40. import java.util.IdentityHashMap;
  41. /**
  42. * @author Robert Schuster (robertschuster@fsfe.org)
  43. * @since 1.4
  44. */
  45. public class Encoder
  46. {
  47. /**
  48. * An internal DefaultPersistenceDelegate instance that is used for every
  49. * class that does not a have a special special PersistenceDelegate.
  50. */
  51. private static PersistenceDelegate defaultPersistenceDelegate;
  52. private static PersistenceDelegate fakePersistenceDelegate;
  53. /**
  54. * Stores the relation Class->PersistenceDelegate.
  55. */
  56. private static HashMap delegates = new HashMap();
  57. /**
  58. * Stores the relation oldInstance->newInstance
  59. */
  60. private IdentityHashMap candidates = new IdentityHashMap();
  61. private ExceptionListener exceptionListener;
  62. /**
  63. * A simple number that is used to restrict the access to writeExpression and
  64. * writeStatement. The rule is that both methods should only be used when an
  65. * object is written to the stream (= writeObject). Therefore accessCounter is
  66. * incremented just before the call to writeObject and decremented afterwards.
  67. * Then writeStatement and writeExpression allow execution only if
  68. * accessCounter is bigger than zero.
  69. */
  70. private int accessCounter = 0;
  71. public Encoder()
  72. {
  73. setupDefaultPersistenceDelegates();
  74. setExceptionListener(null);
  75. }
  76. /**
  77. * Sets up a bunch of {@link PersistenceDelegate} instances which are needed
  78. * for the basic working of a {@link Encoder}s.
  79. */
  80. private static void setupDefaultPersistenceDelegates()
  81. {
  82. synchronized (delegates)
  83. {
  84. if (defaultPersistenceDelegate != null)
  85. return;
  86. delegates.put(Class.class, new ClassPersistenceDelegate());
  87. PersistenceDelegate pd = new PrimitivePersistenceDelegate();
  88. delegates.put(Boolean.class, pd);
  89. delegates.put(Byte.class, pd);
  90. delegates.put(Short.class, pd);
  91. delegates.put(Integer.class, pd);
  92. delegates.put(Long.class, pd);
  93. delegates.put(Float.class, pd);
  94. delegates.put(Double.class, pd);
  95. delegates.put(Object[].class, new ArrayPersistenceDelegate());
  96. pd = new CollectionPersistenceDelegate();
  97. delegates.put(AbstractCollection.class, pd);
  98. pd = new MapPersistenceDelegate();
  99. delegates.put(java.util.AbstractMap.class, pd);
  100. delegates.put(java.util.Hashtable.class, pd);
  101. defaultPersistenceDelegate = new DefaultPersistenceDelegate();
  102. delegates.put(Object.class, defaultPersistenceDelegate);
  103. // Creates a PersistenceDelegate implementation which is
  104. // returned for 'null'. In practice this instance is
  105. // not used in any way and is just here to be compatible
  106. // with the reference implementation which returns a
  107. // similar instance when calling getPersistenceDelegate(null) .
  108. fakePersistenceDelegate = new PersistenceDelegate()
  109. {
  110. protected Expression instantiate(Object o, Encoder e)
  111. {
  112. return null;
  113. }
  114. };
  115. }
  116. }
  117. protected void writeObject(Object o)
  118. {
  119. // 'null' has no PersistenceDelegate and will not
  120. // create an Expression which has to be cloned.
  121. // However subclasses should be aware that writeObject
  122. // may be called with a 'null' argument and should
  123. // write the proper representation of it.
  124. if (o == null)
  125. return;
  126. PersistenceDelegate pd = getPersistenceDelegate(o.getClass());
  127. accessCounter++;
  128. pd.writeObject(o, this);
  129. accessCounter--;
  130. }
  131. /**
  132. * Sets the {@link ExceptionListener} instance to be used for reporting
  133. * recorable exceptions in the instantiation and initialization sequence. If
  134. * the argument is <code>null</code> a default instance will be used that
  135. * prints the thrown exception to <code>System.err</code>.
  136. */
  137. public void setExceptionListener(ExceptionListener listener)
  138. {
  139. exceptionListener = (listener != null)
  140. ? listener : DefaultExceptionListener.INSTANCE;
  141. }
  142. /**
  143. * Returns the currently active {@link ExceptionListener} instance.
  144. */
  145. public ExceptionListener getExceptionListener()
  146. {
  147. return exceptionListener;
  148. }
  149. public PersistenceDelegate getPersistenceDelegate(Class<?> type)
  150. {
  151. // This is not specified but the JDK behaves like this.
  152. if (type == null)
  153. return fakePersistenceDelegate;
  154. // Treats all array classes in the same way and assigns
  155. // them a shared PersistenceDelegate implementation tailored
  156. // for array instantation and initialization.
  157. if (type.isArray())
  158. return (PersistenceDelegate) delegates.get(Object[].class);
  159. PersistenceDelegate pd = (PersistenceDelegate) delegates.get(type);
  160. return (pd != null) ? pd : defaultPersistenceDelegate;
  161. }
  162. /**
  163. * Sets the {@link PersistenceDelegate} instance for the given class.
  164. * <p>
  165. * Note: Throws a <code>NullPointerException</code> if the argument is
  166. * <code>null</code>.
  167. * </p>
  168. * <p>
  169. * Note: Silently ignores PersistenceDelegates for Array types and primitive
  170. * wrapper classes.
  171. * </p>
  172. * <p>
  173. * Note: Although this method is not declared <code>static</code> changes to
  174. * the {@link PersistenceDelegate}s affect <strong>all</strong>
  175. * {@link Encoder} instances. <strong>In this implementation</strong> the
  176. * access is thread safe.
  177. * </p>
  178. */
  179. public void setPersistenceDelegate(Class<?> type,
  180. PersistenceDelegate delegate)
  181. {
  182. // If the argument is null this will cause a NullPointerException
  183. // which is expected behavior.
  184. // This makes custom PDs for array, primitive types and their wrappers
  185. // impossible but this is how the JDK behaves.
  186. if (type.isArray() || type.isPrimitive() || type == Boolean.class
  187. || type == Byte.class || type == Short.class || type == Integer.class
  188. || type == Long.class || type == Float.class || type == Double.class)
  189. return;
  190. synchronized (delegates)
  191. {
  192. delegates.put(type, delegate);
  193. }
  194. }
  195. public Object remove(Object oldInstance)
  196. {
  197. return candidates.remove(oldInstance);
  198. }
  199. /**
  200. * Returns the replacement object which has been created by the encoder during
  201. * the instantiation sequence or <code>null</code> if the object has not
  202. * been processed yet.
  203. * <p>
  204. * Note: The <code>String</code> class acts as an endpoint for the
  205. * inherently recursive algorithm of the {@link Encoder}. Therefore instances
  206. * of <code>String</code> will always be returned by this method. In other
  207. * words the assertion: <code>
  208. * assert (anyEncoder.get(anyString) == anyString)
  209. * </code<
  210. * will always hold.</p>
  211. *
  212. * <p>Note: If <code>null</code> is requested, the result will
  213. * always be <code>null</code>.</p>
  214. */
  215. public Object get(Object oldInstance)
  216. {
  217. // String instances are handled in a special way.
  218. // No one knows why this is not officially specified
  219. // because this is a rather important design decision.
  220. return (oldInstance == null) ? null :
  221. (oldInstance.getClass() == String.class) ?
  222. oldInstance : candidates.get(oldInstance);
  223. }
  224. /**
  225. * <p>
  226. * Note: If you call this method not from within an object instantiation and
  227. * initialization sequence it will be silently ignored.
  228. * </p>
  229. */
  230. public void writeStatement(Statement stmt)
  231. {
  232. // Silently ignore out of bounds calls.
  233. if (accessCounter <= 0)
  234. return;
  235. Object target = stmt.getTarget();
  236. Object newTarget = get(target);
  237. if (newTarget == null)
  238. {
  239. writeObject(target);
  240. newTarget = get(target);
  241. }
  242. Object[] args = stmt.getArguments();
  243. Object[] newArgs = new Object[args.length];
  244. for (int i = 0; i < args.length; i++)
  245. {
  246. newArgs[i] = get(args[i]);
  247. if (newArgs[i] == null || isImmutableType(args[i].getClass()))
  248. {
  249. writeObject(args[i]);
  250. newArgs[i] = get(args[i]);
  251. }
  252. }
  253. Statement newStmt = new Statement(newTarget, stmt.getMethodName(), newArgs);
  254. try
  255. {
  256. newStmt.execute();
  257. }
  258. catch (Exception e)
  259. {
  260. exceptionListener.exceptionThrown(e);
  261. }
  262. }
  263. /**
  264. * <p>
  265. * Note: If you call this method not from within an object instantiation and
  266. * initialization sequence it will be silently ignored.
  267. * </p>
  268. */
  269. public void writeExpression(Expression expr)
  270. {
  271. // Silently ignore out of bounds calls.
  272. if (accessCounter <= 0)
  273. return;
  274. Object target = expr.getTarget();
  275. Object value = null;
  276. Object newValue = null;
  277. try
  278. {
  279. value = expr.getValue();
  280. }
  281. catch (Exception e)
  282. {
  283. exceptionListener.exceptionThrown(e);
  284. return;
  285. }
  286. newValue = get(value);
  287. if (newValue == null)
  288. {
  289. Object newTarget = get(target);
  290. if (newTarget == null)
  291. {
  292. writeObject(target);
  293. newTarget = get(target);
  294. // May happen if exception was thrown.
  295. if (newTarget == null)
  296. {
  297. return;
  298. }
  299. }
  300. Object[] args = expr.getArguments();
  301. Object[] newArgs = new Object[args.length];
  302. for (int i = 0; i < args.length; i++)
  303. {
  304. newArgs[i] = get(args[i]);
  305. if (newArgs[i] == null || isImmutableType(args[i].getClass()))
  306. {
  307. writeObject(args[i]);
  308. newArgs[i] = get(args[i]);
  309. }
  310. }
  311. Expression newExpr = new Expression(newTarget, expr.getMethodName(),
  312. newArgs);
  313. // Fakes the result of Class.forName(<primitiveType>) to make it possible
  314. // to hand such a type to the encoding process.
  315. if (value instanceof Class && ((Class) value).isPrimitive())
  316. newExpr.setValue(value);
  317. // Instantiates the new object.
  318. try
  319. {
  320. newValue = newExpr.getValue();
  321. candidates.put(value, newValue);
  322. }
  323. catch (Exception e)
  324. {
  325. exceptionListener.exceptionThrown(e);
  326. return;
  327. }
  328. writeObject(value);
  329. }
  330. else if(value.getClass() == String.class || value.getClass() == Class.class)
  331. {
  332. writeObject(value);
  333. }
  334. }
  335. /** Returns whether the given class is an immutable
  336. * type which has to be handled differently when serializing it.
  337. *
  338. * <p>Immutable objects always have to be instantiated instead of
  339. * modifying an existing instance.</p>
  340. *
  341. * @param type The class to test.
  342. * @return Whether the first argument is an immutable type.
  343. */
  344. boolean isImmutableType(Class type)
  345. {
  346. return type == String.class || type == Class.class
  347. || type == Integer.class || type == Boolean.class
  348. || type == Byte.class || type == Short.class
  349. || type == Long.class || type == Float.class
  350. || type == Double.class;
  351. }
  352. /** Sets the stream candidate for a given object.
  353. *
  354. * @param oldObject The object given to the encoder.
  355. * @param newObject The object the encoder generated.
  356. */
  357. void putCandidate(Object oldObject, Object newObject)
  358. {
  359. candidates.put(oldObject, newObject);
  360. }
  361. }