1. /*
  2. * @(#)MetaData.java 1.39 04/05/05
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.beans;
  8. import java.lang.reflect.Array;
  9. import java.lang.reflect.Field;
  10. import java.lang.reflect.Method;
  11. import java.util.Vector;
  12. import java.util.Hashtable;
  13. import java.util.Iterator;
  14. import java.util.Enumeration;
  15. /*
  16. * Like the <code>Intropector</code>, the <code>MetaData</code> class
  17. * contains <em>meta</em> objects that describe the way
  18. * classes should express their state in terms of their
  19. * own public APIs.
  20. *
  21. * @see java.beans.Intropector
  22. *
  23. * @version 1.39 05/05/04
  24. * @author Philip Milne
  25. * @author Steve Langley
  26. */
  27. class NullPersistenceDelegate extends PersistenceDelegate {
  28. // Note this will be called by all classes when they reach the
  29. // top of their superclass chain.
  30. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  31. }
  32. protected Expression instantiate(Object oldInstance, Encoder out) { return null; }
  33. public void writeObject(Object oldInstance, Encoder out) {
  34. // System.out.println("NullPersistenceDelegate:writeObject " + oldInstance);
  35. }
  36. }
  37. class PrimitivePersistenceDelegate extends PersistenceDelegate {
  38. protected boolean mutatesTo(Object oldInstance, Object newInstance) {
  39. return oldInstance.equals(newInstance);
  40. }
  41. protected Expression instantiate(Object oldInstance, Encoder out) {
  42. return new Expression(oldInstance, oldInstance.getClass(),
  43. "new", new Object[]{oldInstance.toString()});
  44. }
  45. }
  46. class ArrayPersistenceDelegate extends PersistenceDelegate {
  47. protected boolean mutatesTo(Object oldInstance, Object newInstance) {
  48. return (newInstance != null &&
  49. oldInstance.getClass() == newInstance.getClass() && // Also ensures the subtype is correct.
  50. Array.getLength(oldInstance) == Array.getLength(newInstance));
  51. }
  52. protected Expression instantiate(Object oldInstance, Encoder out) {
  53. // System.out.println("instantiate: " + type + " " + oldInstance);
  54. Class oldClass = oldInstance.getClass();
  55. return new Expression(oldInstance, Array.class, "newInstance",
  56. new Object[]{oldClass.getComponentType(),
  57. new Integer(Array.getLength(oldInstance))});
  58. }
  59. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  60. int n = Array.getLength(oldInstance);
  61. for (int i = 0; i < n; i++) {
  62. Object index = new Integer(i);
  63. // Expression oldGetExp = new Expression(Array.class, "get", new Object[]{oldInstance, index});
  64. // Expression newGetExp = new Expression(Array.class, "get", new Object[]{newInstance, index});
  65. Expression oldGetExp = new Expression(oldInstance, "get", new Object[]{index});
  66. Expression newGetExp = new Expression(newInstance, "get", new Object[]{index});
  67. try {
  68. Object oldValue = oldGetExp.getValue();
  69. Object newValue = newGetExp.getValue();
  70. out.writeExpression(oldGetExp);
  71. if (!MetaData.equals(newValue, out.get(oldValue))) {
  72. // System.out.println("Not equal: " + newGetExp + " != " + actualGetExp);
  73. // invokeStatement(Array.class, "set", new Object[]{oldInstance, index, oldValue}, out);
  74. DefaultPersistenceDelegate.invokeStatement(oldInstance, "set", new Object[]{index, oldValue}, out);
  75. }
  76. }
  77. catch (Exception e) {
  78. // System.err.println("Warning:: failed to write: " + oldGetExp);
  79. out.getExceptionListener().exceptionThrown(e);
  80. }
  81. }
  82. }
  83. }
  84. class ProxyPersistenceDelegate extends PersistenceDelegate {
  85. protected Expression instantiate(Object oldInstance, Encoder out) {
  86. Class type = oldInstance.getClass();
  87. java.lang.reflect.Proxy p = (java.lang.reflect.Proxy)oldInstance;
  88. // This unappealing hack is not required but makes the
  89. // representation of EventHandlers much more concise.
  90. java.lang.reflect.InvocationHandler ih = java.lang.reflect.Proxy.getInvocationHandler(p);
  91. if (ih instanceof EventHandler) {
  92. EventHandler eh = (EventHandler)ih;
  93. Vector args = new Vector();
  94. args.add(type.getInterfaces()[0]);
  95. args.add(eh.getTarget());
  96. args.add(eh.getAction());
  97. if (eh.getEventPropertyName() != null) {
  98. args.add(eh.getEventPropertyName());
  99. }
  100. if (eh.getListenerMethodName() != null) {
  101. args.setSize(4);
  102. args.add(eh.getListenerMethodName());
  103. }
  104. return new Expression(oldInstance,
  105. EventHandler.class,
  106. "create",
  107. args.toArray());
  108. }
  109. return new Expression(oldInstance,
  110. java.lang.reflect.Proxy.class,
  111. "newProxyInstance",
  112. new Object[]{type.getClassLoader(),
  113. type.getInterfaces(),
  114. ih});
  115. }
  116. }
  117. // Strings
  118. class java_lang_String_PersistenceDelegate extends PersistenceDelegate {
  119. protected Expression instantiate(Object oldInstance, Encoder out) { return null; }
  120. public void writeObject(Object oldInstance, Encoder out) {
  121. // System.out.println("NullPersistenceDelegate:writeObject " + oldInstance);
  122. }
  123. }
  124. // Classes
  125. class java_lang_Class_PersistenceDelegate extends PersistenceDelegate {
  126. protected Expression instantiate(Object oldInstance, Encoder out) {
  127. Class c = (Class)oldInstance;
  128. // As of 1.3 it is not possible to call Class.forName("int"),
  129. // so we have to generate different code for primitive types.
  130. // This is needed for arrays whose subtype may be primitive.
  131. if (c.isPrimitive()) {
  132. Field field = null;
  133. try {
  134. field = ReflectionUtils.typeToClass(c).getDeclaredField("TYPE");
  135. } catch (NoSuchFieldException ex) {
  136. System.err.println("Unknown primitive type: " + c);
  137. }
  138. return new Expression(oldInstance, field, "get", new Object[]{null});
  139. }
  140. else if (oldInstance == String.class) {
  141. return new Expression(oldInstance, "", "getClass", new Object[]{});
  142. }
  143. else if (oldInstance == Class.class) {
  144. return new Expression(oldInstance, String.class, "getClass", new Object[]{});
  145. }
  146. else {
  147. return new Expression(oldInstance, Class.class, "forName", new Object[]{c.getName()});
  148. }
  149. }
  150. }
  151. // Fields
  152. class java_lang_reflect_Field_PersistenceDelegate extends PersistenceDelegate {
  153. protected Expression instantiate(Object oldInstance, Encoder out) {
  154. Field f = (Field)oldInstance;
  155. return new Expression(oldInstance,
  156. f.getDeclaringClass(),
  157. "getField",
  158. new Object[]{f.getName()});
  159. }
  160. }
  161. // Methods
  162. class java_lang_reflect_Method_PersistenceDelegate extends PersistenceDelegate {
  163. protected Expression instantiate(Object oldInstance, Encoder out) {
  164. Method m = (Method)oldInstance;
  165. return new Expression(oldInstance,
  166. m.getDeclaringClass(),
  167. "getMethod",
  168. new Object[]{m.getName(), m.getParameterTypes()});
  169. }
  170. }
  171. // Collections
  172. /*
  173. The Hashtable and AbstractMap classes have no common ancestor yet may
  174. be handled with a single persistence delegate: one which uses the methods
  175. of the Map insterface exclusively. Attatching the persistence delegates
  176. to the interfaces themselves is fraught however since, in the case of
  177. the Map, both the AbstractMap and HashMap classes are declared to
  178. implement the Map interface, leaving the obvious implementation prone
  179. to repeating their initialization. These issues and questions around
  180. the ordering of delegates attached to interfaces have lead us to
  181. ignore any delegates attached to interfaces and force all persistence
  182. delegates to be registered with concrete classes.
  183. */
  184. // Collection
  185. class java_util_Collection_PersistenceDelegate extends DefaultPersistenceDelegate {
  186. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  187. java.util.Collection oldO = (java.util.Collection)oldInstance;
  188. java.util.Collection newO = (java.util.Collection)newInstance;
  189. if (newO.size() != 0) {
  190. invokeStatement(oldInstance, "clear", new Object[]{}, out);
  191. }
  192. for (Iterator i = oldO.iterator(); i.hasNext();) {
  193. invokeStatement(oldInstance, "add", new Object[]{i.next()}, out);
  194. }
  195. }
  196. }
  197. // List
  198. class java_util_List_PersistenceDelegate extends DefaultPersistenceDelegate {
  199. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  200. java.util.List oldO = (java.util.List)oldInstance;
  201. java.util.List newO = (java.util.List)newInstance;
  202. int oldSize = oldO.size();
  203. int newSize = (newO == null) ? 0 : newO.size();
  204. if (oldSize < newSize) {
  205. invokeStatement(oldInstance, "clear", new Object[]{}, out);
  206. newSize = 0;
  207. }
  208. for (int i = 0; i < newSize; i++) {
  209. Object index = new Integer(i);
  210. Expression oldGetExp = new Expression(oldInstance, "get", new Object[]{index});
  211. Expression newGetExp = new Expression(newInstance, "get", new Object[]{index});
  212. try {
  213. Object oldValue = oldGetExp.getValue();
  214. Object newValue = newGetExp.getValue();
  215. out.writeExpression(oldGetExp);
  216. if (!MetaData.equals(newValue, out.get(oldValue))) {
  217. invokeStatement(oldInstance, "set", new Object[]{index, oldValue}, out);
  218. }
  219. }
  220. catch (Exception e) {
  221. out.getExceptionListener().exceptionThrown(e);
  222. }
  223. }
  224. for (int i = newSize; i < oldSize; i++) {
  225. invokeStatement(oldInstance, "add", new Object[]{oldO.get(i)}, out);
  226. }
  227. }
  228. }
  229. // Map
  230. class java_util_Map_PersistenceDelegate extends DefaultPersistenceDelegate {
  231. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  232. // System.out.println("Initializing: " + newInstance);
  233. java.util.Map oldMap = (java.util.Map)oldInstance;
  234. java.util.Map newMap = (java.util.Map)newInstance;
  235. // Remove the new elements.
  236. // Do this first otherwise we undo the adding work.
  237. if (newMap != null) {
  238. java.util.Iterator newKeys = newMap.keySet().iterator();
  239. while(newKeys.hasNext()) {
  240. Object newKey = newKeys.next();
  241. // PENDING: This "key" is not in the right environment.
  242. if (!oldMap.containsKey(newKey)) {
  243. invokeStatement(oldInstance, "remove", new Object[]{newKey}, out);
  244. }
  245. }
  246. }
  247. // Add the new elements.
  248. java.util.Iterator oldKeys = oldMap.keySet().iterator();
  249. while(oldKeys.hasNext()) {
  250. Object oldKey = oldKeys.next();
  251. Expression oldGetExp = new Expression(oldInstance, "get", new Object[]{oldKey});
  252. // Pending: should use newKey.
  253. Expression newGetExp = new Expression(newInstance, "get", new Object[]{oldKey});
  254. try {
  255. Object oldValue = oldGetExp.getValue();
  256. Object newValue = newGetExp.getValue();
  257. out.writeExpression(oldGetExp);
  258. if (!MetaData.equals(newValue, out.get(oldValue))) {
  259. invokeStatement(oldInstance, "put", new Object[]{oldKey, oldValue}, out);
  260. }
  261. }
  262. catch (Exception e) {
  263. out.getExceptionListener().exceptionThrown(e);
  264. }
  265. }
  266. }
  267. }
  268. class java_util_AbstractCollection_PersistenceDelegate extends java_util_Collection_PersistenceDelegate {}
  269. class java_util_AbstractList_PersistenceDelegate extends java_util_List_PersistenceDelegate {}
  270. class java_util_AbstractMap_PersistenceDelegate extends java_util_Map_PersistenceDelegate {}
  271. class java_util_Hashtable_PersistenceDelegate extends java_util_Map_PersistenceDelegate {}
  272. // Beans
  273. class java_beans_beancontext_BeanContextSupport_PersistenceDelegate extends java_util_Collection_PersistenceDelegate {}
  274. // AWT
  275. class StaticFieldsPersistenceDelegate extends PersistenceDelegate {
  276. protected void installFields(Encoder out, Class<?> cls) {
  277. Field fields[] = cls.getFields();
  278. for(int i = 0; i < fields.length; i++) {
  279. Field field = fields[i];
  280. // Don't install primitives, their identity will not be preserved
  281. // by wrapping.
  282. if (Object.class.isAssignableFrom(field.getType())) {
  283. out.writeExpression(new Expression(field, "get", new Object[]{null}));
  284. }
  285. }
  286. }
  287. protected Expression instantiate(Object oldInstance, Encoder out) {
  288. throw new RuntimeException("Unrecognized instance: " + oldInstance);
  289. }
  290. public void writeObject(Object oldInstance, Encoder out) {
  291. if (out.getAttribute(this) == null) {
  292. out.setAttribute(this, Boolean.TRUE);
  293. installFields(out, oldInstance.getClass());
  294. }
  295. super.writeObject(oldInstance, out);
  296. }
  297. }
  298. // SystemColor
  299. class java_awt_SystemColor_PersistenceDelegate extends StaticFieldsPersistenceDelegate {}
  300. // TextAttribute
  301. class java_awt_font_TextAttribute_PersistenceDelegate extends StaticFieldsPersistenceDelegate {}
  302. // MenuShortcut
  303. class java_awt_MenuShortcut_PersistenceDelegate extends PersistenceDelegate {
  304. protected Expression instantiate(Object oldInstance, Encoder out) {
  305. java.awt.MenuShortcut m = (java.awt.MenuShortcut)oldInstance;
  306. return new Expression(oldInstance, m.getClass(), "new",
  307. new Object[]{new Integer(m.getKey()), Boolean.valueOf(m.usesShiftModifier())});
  308. }
  309. }
  310. // Component
  311. class java_awt_Component_PersistenceDelegate extends DefaultPersistenceDelegate {
  312. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  313. super.initialize(type, oldInstance, newInstance, out);
  314. java.awt.Component c = (java.awt.Component)oldInstance;
  315. java.awt.Component c2 = (java.awt.Component)newInstance;
  316. // The "background", "foreground" and "font" properties.
  317. // The foreground and font properties of Windows change from
  318. // null to defined values after the Windows are made visible -
  319. // special case them for now.
  320. if (!(oldInstance instanceof java.awt.Window)) {
  321. String[] fieldNames = new String[]{"background", "foreground", "font"};
  322. for(int i = 0; i < fieldNames.length; i++) {
  323. String name = fieldNames[i];
  324. Object oldValue = ReflectionUtils.getPrivateField(oldInstance, java.awt.Component.class, name, out.getExceptionListener());
  325. Object newValue = (newInstance == null) ? null : ReflectionUtils.getPrivateField(newInstance, java.awt.Component.class, name, out.getExceptionListener());
  326. if (oldValue != null && !oldValue.equals(newValue)) {
  327. invokeStatement(oldInstance, "set" + NameGenerator.capitalize(name), new Object[]{oldValue}, out);
  328. }
  329. }
  330. }
  331. // Bounds
  332. java.awt.Container p = c.getParent();
  333. if (p == null || p.getLayout() == null && !(p instanceof javax.swing.JLayeredPane)) {
  334. // Use the most concise construct.
  335. boolean locationCorrect = c.getLocation().equals(c2.getLocation());
  336. boolean sizeCorrect = c.getSize().equals(c2.getSize());
  337. if (!locationCorrect && !sizeCorrect) {
  338. invokeStatement(oldInstance, "setBounds", new Object[]{c.getBounds()}, out);
  339. }
  340. else if (!locationCorrect) {
  341. invokeStatement(oldInstance, "setLocation", new Object[]{c.getLocation()}, out);
  342. }
  343. else if (!sizeCorrect) {
  344. invokeStatement(oldInstance, "setSize", new Object[]{c.getSize()}, out);
  345. }
  346. }
  347. }
  348. }
  349. // Container
  350. class java_awt_Container_PersistenceDelegate extends DefaultPersistenceDelegate {
  351. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  352. super.initialize(type, oldInstance, newInstance, out);
  353. // Ignore the children of a JScrollPane.
  354. // Pending(milne) find a better way to do this.
  355. if (oldInstance instanceof javax.swing.JScrollPane) {
  356. return;
  357. }
  358. java.awt.Container oldC = (java.awt.Container)oldInstance;
  359. java.awt.Component[] oldChildren = oldC.getComponents();
  360. java.awt.Container newC = (java.awt.Container)newInstance;
  361. java.awt.Component[] newChildren = (newC == null) ? new java.awt.Component[0] : newC.getComponents();
  362. // Pending. Assume all the new children are unaltered.
  363. for(int i = newChildren.length; i < oldChildren.length; i++) {
  364. invokeStatement(oldInstance, "add", new Object[]{oldChildren[i]}, out);
  365. }
  366. }
  367. }
  368. // Choice
  369. class java_awt_Choice_PersistenceDelegate extends DefaultPersistenceDelegate {
  370. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  371. super.initialize(type, oldInstance, newInstance, out);
  372. java.awt.Choice m = (java.awt.Choice)oldInstance;
  373. java.awt.Choice n = (java.awt.Choice)newInstance;
  374. for (int i = n.getItemCount(); i < m.getItemCount(); i++) {
  375. invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out);
  376. }
  377. }
  378. }
  379. // Menu
  380. class java_awt_Menu_PersistenceDelegate extends DefaultPersistenceDelegate {
  381. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  382. super.initialize(type, oldInstance, newInstance, out);
  383. java.awt.Menu m = (java.awt.Menu)oldInstance;
  384. java.awt.Menu n = (java.awt.Menu)newInstance;
  385. for (int i = n.getItemCount(); i < m.getItemCount(); i++) {
  386. invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out);
  387. }
  388. }
  389. }
  390. // MenuBar
  391. class java_awt_MenuBar_PersistenceDelegate extends DefaultPersistenceDelegate {
  392. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  393. super.initialize(type, oldInstance, newInstance, out);
  394. java.awt.MenuBar m = (java.awt.MenuBar)oldInstance;
  395. java.awt.MenuBar n = (java.awt.MenuBar)newInstance;
  396. for (int i = n.getMenuCount(); i < m.getMenuCount(); i++) {
  397. invokeStatement(oldInstance, "add", new Object[]{m.getMenu(i)}, out);
  398. }
  399. }
  400. }
  401. // List
  402. class java_awt_List_PersistenceDelegate extends DefaultPersistenceDelegate {
  403. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  404. super.initialize(type, oldInstance, newInstance, out);
  405. java.awt.List m = (java.awt.List)oldInstance;
  406. java.awt.List n = (java.awt.List)newInstance;
  407. for (int i = n.getItemCount(); i < m.getItemCount(); i++) {
  408. invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out);
  409. }
  410. }
  411. }
  412. // LayoutManagers
  413. // BorderLayout
  414. class java_awt_BorderLayout_PersistenceDelegate extends DefaultPersistenceDelegate {
  415. protected void initialize(Class<?> type, Object oldInstance,
  416. Object newInstance, Encoder out) {
  417. super.initialize(type, oldInstance, newInstance, out);
  418. String[] locations = {"north", "south", "east", "west", "center"};
  419. String[] names = {java.awt.BorderLayout.NORTH, java.awt.BorderLayout.SOUTH,
  420. java.awt.BorderLayout.EAST, java.awt.BorderLayout.WEST,
  421. java.awt.BorderLayout.CENTER};
  422. for(int i = 0; i < locations.length; i++) {
  423. Object oldC = ReflectionUtils.getPrivateField(oldInstance,
  424. java.awt.BorderLayout.class,
  425. locations[i],
  426. out.getExceptionListener());
  427. Object newC = ReflectionUtils.getPrivateField(newInstance,
  428. java.awt.BorderLayout.class,
  429. locations[i],
  430. out.getExceptionListener());
  431. // Pending, assume any existing elements are OK.
  432. if (oldC != null && newC == null) {
  433. invokeStatement(oldInstance, "addLayoutComponent",
  434. new Object[]{oldC, names[i]}, out);
  435. }
  436. }
  437. }
  438. }
  439. // CardLayout
  440. class java_awt_CardLayout_PersistenceDelegate extends DefaultPersistenceDelegate {
  441. protected void initialize(Class<?> type, Object oldInstance,
  442. Object newInstance, Encoder out) {
  443. super.initialize(type, oldInstance, newInstance, out);
  444. Hashtable tab = (Hashtable)ReflectionUtils.getPrivateField(oldInstance,
  445. java.awt.CardLayout.class,
  446. "tab",
  447. out.getExceptionListener());
  448. if (tab != null) {
  449. for(Enumeration e = tab.keys(); e.hasMoreElements();) {
  450. Object child = e.nextElement();
  451. invokeStatement(oldInstance, "addLayoutComponent",
  452. new Object[]{child, (String)tab.get(child)}, out);
  453. }
  454. }
  455. }
  456. }
  457. // GridBagLayout
  458. class java_awt_GridBagLayout_PersistenceDelegate extends DefaultPersistenceDelegate {
  459. protected void initialize(Class<?> type, Object oldInstance,
  460. Object newInstance, Encoder out) {
  461. super.initialize(type, oldInstance, newInstance, out);
  462. Hashtable comptable = (Hashtable)ReflectionUtils.getPrivateField(oldInstance,
  463. java.awt.GridBagLayout.class,
  464. "comptable",
  465. out.getExceptionListener());
  466. if (comptable != null) {
  467. for(Enumeration e = comptable.keys(); e.hasMoreElements();) {
  468. Object child = e.nextElement();
  469. invokeStatement(oldInstance, "addLayoutComponent",
  470. new Object[]{child, comptable.get(child)}, out);
  471. }
  472. }
  473. }
  474. }
  475. // Swing
  476. // JFrame (If we do this for Window instead of JFrame, the setVisible call
  477. // will be issued before we have added all the children to the JFrame and
  478. // will appear blank).
  479. class javax_swing_JFrame_PersistenceDelegate extends DefaultPersistenceDelegate {
  480. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  481. super.initialize(type, oldInstance, newInstance, out);
  482. java.awt.Window oldC = (java.awt.Window)oldInstance;
  483. java.awt.Window newC = (java.awt.Window)newInstance;
  484. boolean oldV = oldC.isVisible();
  485. boolean newV = newC.isVisible();
  486. if (newV != oldV) {
  487. // false means: don't execute this statement at write time.
  488. boolean executeStatements = out.executeStatements;
  489. out.executeStatements = false;
  490. invokeStatement(oldInstance, "setVisible", new Object[]{Boolean.valueOf(oldV)}, out);
  491. out.executeStatements = executeStatements;
  492. }
  493. }
  494. }
  495. // Models
  496. // DefaultListModel
  497. class javax_swing_DefaultListModel_PersistenceDelegate extends DefaultPersistenceDelegate {
  498. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  499. // Note, the "size" property will be set here.
  500. super.initialize(type, oldInstance, newInstance, out);
  501. javax.swing.DefaultListModel m = (javax.swing.DefaultListModel)oldInstance;
  502. javax.swing.DefaultListModel n = (javax.swing.DefaultListModel)newInstance;
  503. for (int i = n.getSize(); i < m.getSize(); i++) {
  504. invokeStatement(oldInstance, "add", // Can also use "addElement".
  505. new Object[]{m.getElementAt(i)}, out);
  506. }
  507. }
  508. }
  509. // DefaultComboBoxModel
  510. class javax_swing_DefaultComboBoxModel_PersistenceDelegate extends DefaultPersistenceDelegate {
  511. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  512. super.initialize(type, oldInstance, newInstance, out);
  513. javax.swing.DefaultComboBoxModel m = (javax.swing.DefaultComboBoxModel)oldInstance;
  514. for (int i = 0; i < m.getSize(); i++) {
  515. invokeStatement(oldInstance, "addElement", new Object[]{m.getElementAt(i)}, out);
  516. }
  517. }
  518. }
  519. // DefaultMutableTreeNode
  520. class javax_swing_tree_DefaultMutableTreeNode_PersistenceDelegate extends DefaultPersistenceDelegate {
  521. protected void initialize(Class<?> type, Object oldInstance, Object
  522. newInstance, Encoder out) {
  523. super.initialize(type, oldInstance, newInstance, out);
  524. javax.swing.tree.DefaultMutableTreeNode m =
  525. (javax.swing.tree.DefaultMutableTreeNode)oldInstance;
  526. javax.swing.tree.DefaultMutableTreeNode n =
  527. (javax.swing.tree.DefaultMutableTreeNode)newInstance;
  528. for (int i = n.getChildCount(); i < m.getChildCount(); i++) {
  529. invokeStatement(oldInstance, "add", new
  530. Object[]{m.getChildAt(i)}, out);
  531. }
  532. }
  533. }
  534. // ToolTipManager
  535. class javax_swing_ToolTipManager_PersistenceDelegate extends PersistenceDelegate {
  536. protected Expression instantiate(Object oldInstance, Encoder out) {
  537. return new Expression(oldInstance, javax.swing.ToolTipManager.class,
  538. "sharedInstance", new Object[]{});
  539. }
  540. }
  541. // JTabbedPane
  542. class javax_swing_JTabbedPane_PersistenceDelegate extends DefaultPersistenceDelegate {
  543. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  544. super.initialize(type, oldInstance, newInstance, out);
  545. javax.swing.JTabbedPane p = (javax.swing.JTabbedPane)oldInstance;
  546. for (int i = 0; i < p.getTabCount(); i++) {
  547. invokeStatement(oldInstance, "addTab",
  548. new Object[]{
  549. p.getTitleAt(i),
  550. p.getIconAt(i),
  551. p.getComponentAt(i)}, out);
  552. }
  553. }
  554. }
  555. // Box
  556. class javax_swing_Box_PersistenceDelegate extends DefaultPersistenceDelegate {
  557. protected Expression instantiate(Object oldInstance, Encoder out) {
  558. javax.swing.BoxLayout lm = (javax.swing.BoxLayout)((javax.swing.Box)oldInstance).getLayout();
  559. Object value = ReflectionUtils.getPrivateField(lm, javax.swing.BoxLayout.class, "axis",
  560. out.getExceptionListener());
  561. String method = ((Integer)value).intValue() == javax.swing.BoxLayout.X_AXIS ?
  562. "createHorizontalBox" : "createVerticalBox";
  563. return new Expression(oldInstance, oldInstance.getClass(), method, new Object[0]);
  564. }
  565. }
  566. // JMenu
  567. // Note that we do not need to state the initialiser for
  568. // JMenuItems since the getComponents() method defined in
  569. // Container will return all of the sub menu items that
  570. // need to be added to the menu item.
  571. // Not so for JMenu apparently.
  572. class javax_swing_JMenu_PersistenceDelegate extends DefaultPersistenceDelegate {
  573. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  574. super.initialize(type, oldInstance, newInstance, out);
  575. javax.swing.JMenu m = (javax.swing.JMenu)oldInstance;
  576. java.awt.Component[] c = m.getMenuComponents();
  577. for (int i = 0; i < c.length; i++) {
  578. invokeStatement(oldInstance, "add", new Object[]{c[i]}, out);
  579. }
  580. }
  581. }
  582. /* XXX - doens't seem to work. Debug later.
  583. class javax_swing_JMenu_PersistenceDelegate extends DefaultPersistenceDelegate {
  584. protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
  585. super.initialize(type, oldInstance, newInstance, out);
  586. javax.swing.JMenu m = (javax.swing.JMenu)oldInstance;
  587. javax.swing.JMenu n = (javax.swing.JMenu)newInstance;
  588. for (int i = n.getItemCount(); i < m.getItemCount(); i++) {
  589. invokeStatement(oldInstance, "add", new Object[]{m.getItem(i)}, out);
  590. }
  591. }
  592. }
  593. */
  594. class MetaData {
  595. private static Hashtable internalPersistenceDelegates = new Hashtable();
  596. private static Hashtable transientProperties = new Hashtable();
  597. private static PersistenceDelegate nullPersistenceDelegate = new NullPersistenceDelegate();
  598. private static PersistenceDelegate primitivePersistenceDelegate = new PrimitivePersistenceDelegate();
  599. private static PersistenceDelegate defaultPersistenceDelegate = new DefaultPersistenceDelegate();
  600. private static PersistenceDelegate arrayPersistenceDelegate;
  601. private static PersistenceDelegate proxyPersistenceDelegate;
  602. static {
  603. // Constructors.
  604. // util
  605. registerConstructor("java.util.Date", new String[]{"time"});
  606. // beans
  607. registerConstructor("java.beans.Statement", new String[]{"target", "methodName", "arguments"});
  608. registerConstructor("java.beans.Expression", new String[]{"target", "methodName", "arguments"});
  609. registerConstructor("java.beans.EventHandler", new String[]{"target", "action", "eventPropertyName", "listenerMethodName"});
  610. // awt
  611. registerConstructor("java.awt.Point", new String[]{"x", "y"});
  612. registerConstructor("java.awt.Dimension", new String[]{"width", "height"});
  613. registerConstructor("java.awt.Rectangle", new String[]{"x", "y", "width", "height"});
  614. registerConstructor("java.awt.Insets", new String[]{"top", "left", "bottom", "right"});
  615. registerConstructor("java.awt.Color", new String[]{"red", "green", "blue", "alpha"});
  616. registerConstructor("java.awt.Font", new String[]{"name", "style", "size"});
  617. registerConstructor("java.awt.Cursor", new String[]{"type"});
  618. registerConstructor("java.awt.GridBagConstraints",
  619. new String[]{"gridx", "gridy", "gridwidth", "gridheight",
  620. "weightx", "weighty",
  621. "anchor", "fill", "insets",
  622. "ipadx", "ipady"});
  623. registerConstructor("java.awt.ScrollPane", new String[]{"scrollbarDisplayPolicy"});
  624. // swing
  625. registerConstructor("javax.swing.plaf.FontUIResource", new String[]{"name", "style", "size"});
  626. registerConstructor("javax.swing.plaf.ColorUIResource", new String[]{"red", "green", "blue"});
  627. registerConstructor("javax.swing.tree.DefaultTreeModel", new String[]{"root"});
  628. registerConstructor("javax.swing.JTree", new String[]{"model"});
  629. registerConstructor("javax.swing.tree.TreePath", new String[]{"path"});
  630. registerConstructor("javax.swing.OverlayLayout", new String[]{"target"});
  631. registerConstructor("javax.swing.BoxLayout", new String[]{"target", "axis"});
  632. registerConstructor("javax.swing.Box$Filler", new String[]{"minimumSize", "preferredSize",
  633. "maximumSize"});
  634. registerConstructor("javax.swing.DefaultCellEditor", new String[]{"component"});
  635. /*
  636. This is required because the JSplitPane reveals a private layout class
  637. called BasicSplitPaneUI$BasicVerticalLayoutManager which changes with
  638. the orientation. To avoid the necessity for instantiating it we cause
  639. the orientation attribute to get set before the layout manager - that
  640. way the layout manager will be changed as a side effect. Unfortunately,
  641. the layout property belongs to the superclass and therefore precedes
  642. the orientation property. PENDING - we need to allow this kind of
  643. modification. For now, put the property in the constructor.
  644. */
  645. registerConstructor("javax.swing.JSplitPane", new String[]{"orientation"});
  646. // Try to synthesize the ImageIcon from its description.
  647. registerConstructor("javax.swing.ImageIcon", new String[]{"description"});
  648. // JButton's "label" and "actionCommand" properties are related,
  649. // use the label as a constructor argument to ensure that it is set first.
  650. // This remove the benign, but unnecessary, manipulation of actionCommand
  651. // property in the common case.
  652. registerConstructor("javax.swing.JButton", new String[]{"label"});
  653. // borders
  654. registerConstructor("javax.swing.border.BevelBorder", new String[]{"bevelType", "highlightOuter", "highlightInner", "shadowOuter", "shadowInner"});
  655. registerConstructor("javax.swing.plaf.BorderUIResource$BevelBorderUIResource", new String[]{"bevelType", "highlightOuter", "highlightInner", "shadowOuter", "shadowInner"});
  656. registerConstructor("javax.swing.border.CompoundBorder", new String[]{"outsideBorder", "insideBorder"});
  657. registerConstructor("javax.swing.plaf.BorderUIResource$CompoundBorderUIResource", new String[]{"outsideBorder", "insideBorder"});
  658. registerConstructor("javax.swing.border.EmptyBorder", new String[]{"top", "left", "bottom", "right"});
  659. registerConstructor("javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new String[]{"top", "left", "bottom", "right"});
  660. registerConstructor("javax.swing.border.EtchedBorder", new String[]{"etchType", "highlight", "shadow"});
  661. registerConstructor("javax.swing.plaf.BorderUIResource$EtchedBorderUIResource", new String[]{"etchType", "highlight", "shadow"});
  662. registerConstructor("javax.swing.border.LineBorder", new String[]{"lineColor", "thickness"});
  663. registerConstructor("javax.swing.plaf.BorderUIResource$LineBorderUIResource", new String[]{"lineColor", "thickness"});
  664. // Note this should check to see which of "color" and "tileIcon" is non-null.
  665. registerConstructor("javax.swing.border.MatteBorder", new String[]{"top", "left", "bottom", "right", "tileIcon"});
  666. registerConstructor("javax.swing.plaf.BorderUIResource$MatteBorderUIResource", new String[]{"top", "left", "bottom", "right", "tileIcon"});
  667. registerConstructor("javax.swing.border.SoftBevelBorder", new String[]{"bevelType", "highlightOuter", "highlightInner", "shadowOuter", "shadowInner"});
  668. // registerConstructorWithBadEqual("javax.swing.plaf.BorderUIResource$SoftBevelBorderUIResource", new String[]{"bevelType", "highlightOuter", "highlightInner", "shadowOuter", "shadowInner"});
  669. registerConstructor("javax.swing.border.TitledBorder", new String[]{"border", "title", "titleJustification", "titlePosition", "titleFont", "titleColor"});
  670. registerConstructor("javax.swing.plaf.BorderUIResource$TitledBorderUIResource", new String[]{"border", "title", "titleJustification", "titlePosition", "titleFont", "titleColor"});
  671. // Transient properties
  672. // awt
  673. // Infinite graphs.
  674. removeProperty("java.awt.geom.RectangularShape", "frame");
  675. // removeProperty("java.awt.Rectangle2D", "frame");
  676. // removeProperty("java.awt.Rectangle", "frame");
  677. removeProperty("java.awt.Rectangle", "bounds");
  678. removeProperty("java.awt.Dimension", "size");
  679. removeProperty("java.awt.Point", "location");
  680. // The color and font properties in Component need special treatment, see above.
  681. removeProperty("java.awt.Component", "foreground");
  682. removeProperty("java.awt.Component", "background");
  683. removeProperty("java.awt.Component", "font");
  684. // The visible property of Component needs special treatment because of Windows.
  685. removeProperty("java.awt.Component", "visible");
  686. // This property throws an exception if accessed when there is no child.
  687. removeProperty("java.awt.ScrollPane", "scrollPosition");
  688. // 4917458 this should be removed for XAWT since it may throw
  689. // an unsupported exception if there isn't any input methods.
  690. // This shouldn't be a problem since these are added behind
  691. // the scenes automatically.
  692. removeProperty("java.awt.im.InputContext", "compositionEnabled");
  693. // swing
  694. // The size properties in JComponent need special treatment, see above.
  695. removeProperty("javax.swing.JComponent", "minimumSize");
  696. removeProperty("javax.swing.JComponent", "preferredSize");
  697. removeProperty("javax.swing.JComponent", "maximumSize");
  698. // These properties have platform specific implementations
  699. // and should not appear in archives.
  700. removeProperty("javax.swing.ImageIcon", "image");
  701. removeProperty("javax.swing.ImageIcon", "imageObserver");
  702. // This property throws an exception when set in JMenu.
  703. // PENDING: Note we must delete the property from
  704. // the superclass even though the superclass's
  705. // implementation does not throw an error.
  706. // This needs some more thought.
  707. removeProperty("javax.swing.JMenu", "accelerator");
  708. removeProperty("javax.swing.JMenuItem", "accelerator");
  709. // This property unconditionally throws a "not implemented" exception.
  710. removeProperty("javax.swing.JMenuBar", "helpMenu");
  711. // The scrollBars in a JScrollPane are dynamic and should not
  712. // be archived. The row and columns headers are changed by
  713. // components like JTable on "addNotify".
  714. removeProperty("javax.swing.JScrollPane", "verticalScrollBar");
  715. removeProperty("javax.swing.JScrollPane", "horizontalScrollBar");
  716. removeProperty("javax.swing.JScrollPane", "rowHeader");
  717. removeProperty("javax.swing.JScrollPane", "columnHeader");
  718. removeProperty("javax.swing.JViewport", "extentSize");
  719. // Renderers need special treatment, since their properties
  720. // change during rendering.
  721. removeProperty("javax.swing.table.JTableHeader", "defaultRenderer");
  722. removeProperty("javax.swing.JList", "cellRenderer");
  723. removeProperty("javax.swing.JList", "selectedIndices");
  724. // The lead and anchor selection indexes are best ignored.
  725. // Selection is rarely something that should persist from
  726. // development to deployment.
  727. removeProperty("javax.swing.DefaultListSelectionModel", "leadSelectionIndex");
  728. removeProperty("javax.swing.DefaultListSelectionModel", "anchorSelectionIndex");
  729. // The selection must come after the text itself.
  730. removeProperty("javax.swing.JComboBox", "selectedIndex");
  731. // All selection information should come after the JTabbedPane is built
  732. removeProperty("javax.swing.JTabbedPane", "selectedIndex");
  733. removeProperty("javax.swing.JTabbedPane", "selectedComponent");
  734. // PENDING: The "disabledIcon" property is often computed from the icon property.
  735. removeProperty("javax.swing.AbstractButton", "disabledIcon");
  736. removeProperty("javax.swing.JLabel", "disabledIcon");
  737. // The caret property throws errors when it it set beyond
  738. // the extent of the text. We could just set it after the
  739. // text, but this is probably not something we want to archive anyway.
  740. removeProperty("javax.swing.text.JTextComponent", "caret");
  741. removeProperty("javax.swing.text.JTextComponent", "caretPosition");
  742. // The selectionStart must come after the text itself.
  743. removeProperty("javax.swing.text.JTextComponent", "selectionStart");
  744. removeProperty("javax.swing.text.JTextComponent", "selectionEnd");
  745. }
  746. /*pp*/ static boolean equals(Object o1, Object o2) {
  747. return (o1 == null) ? (o2 == null) : o1.equals(o2);
  748. }
  749. // Entry points for Encoder.
  750. public synchronized static void setPersistenceDelegate(Class type,
  751. PersistenceDelegate persistenceDelegate) {
  752. setBeanAttribute(type, "persistenceDelegate", persistenceDelegate);
  753. }
  754. public synchronized static PersistenceDelegate getPersistenceDelegate(Class type) {
  755. if (type == null) {
  756. return nullPersistenceDelegate;
  757. }
  758. if (ReflectionUtils.isPrimitive(type)) {
  759. return primitivePersistenceDelegate;
  760. }
  761. // The persistence delegate for arrays is non-trivial; instantiate it lazily.
  762. if (type.isArray()) {
  763. if (arrayPersistenceDelegate == null) {
  764. arrayPersistenceDelegate = new ArrayPersistenceDelegate();
  765. }
  766. return arrayPersistenceDelegate;
  767. }
  768. // Handle proxies lazily for backward compatibility with 1.2.
  769. try {
  770. if (java.lang.reflect.Proxy.isProxyClass(type)) {
  771. if (proxyPersistenceDelegate == null) {
  772. proxyPersistenceDelegate = new ProxyPersistenceDelegate();
  773. }
  774. return proxyPersistenceDelegate;
  775. }
  776. }
  777. catch(Exception e) {}
  778. // else if (type.getDeclaringClass() != null) {
  779. // return new DefaultPersistenceDelegate(new String[]{"this$0"});
  780. // }
  781. String typeName = type.getName();
  782. // Check to see if there are properties that have been lazily registered for removal.
  783. if (getBeanAttribute(type, "transient_init") == null) {
  784. Vector tp = (Vector)transientProperties.get(typeName);
  785. if (tp != null) {
  786. for(int i = 0; i < tp.size(); i++) {
  787. setPropertyAttribute(type, (String)tp.get(i), "transient", Boolean.TRUE);
  788. }
  789. }
  790. setBeanAttribute(type, "transient_init", Boolean.TRUE);
  791. }
  792. PersistenceDelegate pd = (PersistenceDelegate)getBeanAttribute(type, "persistenceDelegate");
  793. if (pd == null) {
  794. pd = (PersistenceDelegate)internalPersistenceDelegates.get(typeName);
  795. if (pd != null) {
  796. return pd;
  797. }
  798. internalPersistenceDelegates.put(typeName, defaultPersistenceDelegate);
  799. try {
  800. String name = type.getName();
  801. Class c = Class.forName("java.beans." + name.replace('.', '_')
  802. + "_PersistenceDelegate");
  803. pd = (PersistenceDelegate)c.newInstance();
  804. internalPersistenceDelegates.put(typeName, pd);
  805. }
  806. catch (ClassNotFoundException e) {}
  807. catch (Exception e) {
  808. System.err.println("Internal error: " + e);
  809. }
  810. }
  811. return (pd != null) ? pd : defaultPersistenceDelegate;
  812. }
  813. // Wrapper for Introspector.getBeanInfo to handle exception handling.
  814. // Note: this relys on new 1.4 Introspector semantics which cache the BeanInfos
  815. public static BeanInfo getBeanInfo(Class type) {
  816. BeanInfo info = null;
  817. try {
  818. info = Introspector.getBeanInfo(type);
  819. } catch (Throwable e) {
  820. e.printStackTrace();
  821. }
  822. return info;
  823. }
  824. private static PropertyDescriptor getPropertyDescriptor(Class type, String propertyName) {
  825. BeanInfo info = getBeanInfo(type);
  826. PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
  827. // System.out.println("Searching for: " + propertyName + " in " + type);
  828. for(int i = 0; i < propertyDescriptors.length; i++) {
  829. PropertyDescriptor pd = propertyDescriptors[i];
  830. if (propertyName.equals(pd.getName())) {
  831. return pd;
  832. }
  833. }
  834. return null;
  835. }
  836. private static void setPropertyAttribute(Class type, String property, String attribute, Object value) {
  837. PropertyDescriptor pd = getPropertyDescriptor(type, property);
  838. if (pd == null) {
  839. System.err.println("Warning: property " + property + " is not defined on " + type);
  840. return;
  841. }
  842. pd.setValue(attribute, value);
  843. }
  844. private static void setBeanAttribute(Class type, String attribute, Object value) {
  845. getBeanInfo(type).getBeanDescriptor().setValue(attribute, value);
  846. }
  847. private static Object getBeanAttribute(Class type, String attribute) {
  848. return getBeanInfo(type).getBeanDescriptor().getValue(attribute);
  849. }
  850. // MetaData registration
  851. private synchronized static void registerConstructor(String typeName,
  852. String[] constructor) {
  853. internalPersistenceDelegates.put(typeName,
  854. new DefaultPersistenceDelegate(constructor));
  855. }
  856. private static void removeProperty(String typeName, String property) {
  857. Vector tp = (Vector)transientProperties.get(typeName);
  858. if (tp == null) {
  859. tp = new Vector();
  860. transientProperties.put(typeName, tp);
  861. }
  862. tp.add(property);
  863. }
  864. }