KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > BeanSupport


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.form;
21
22 import java.awt.*;
23 import java.beans.*;
24 import java.lang.reflect.Method JavaDoc;
25 import java.lang.ref.Reference JavaDoc;
26 import java.lang.ref.SoftReference JavaDoc;
27 import java.util.*;
28 import org.netbeans.modules.form.fakepeer.FakePeerSupport;
29 import org.openide.util.Utilities;
30
31 /**
32  * BeanSupport is a utility class with various static methods supporting
33  * operations with JavaBeans.
34  *
35  * @author Ian Formanek, Jan Stola
36  */

37 public class BeanSupport
38 {
39     public static final Object JavaDoc NO_VALUE = new Object JavaDoc();
40
41     // -----------------------------------------------------------------------------
42
// Private variables
43

44     private static Map errorEmptyMap = new HashMap(3);
45     private static Map valuesCache = new HashMap(30);
46     private static Map instancesCache = new HashMap(30);
47     private static Map deviationsCache = new HashMap();
48
49     // -----------------------------------------------------------------------------
50
// Public methods
51

52     /**
53      * Utility method to create an instance of given class. Returns null on
54      * error.
55      * @param beanClass the class to create inctance of
56      * @return new instance of specified class or null if an error occured
57      * during instantiation
58      */

59     public static Object JavaDoc createBeanInstance(Class JavaDoc beanClass) {
60         try {
61             return CreationFactory.createDefaultInstance(beanClass);
62         }
63         catch (Exception JavaDoc ex) {
64             if (Boolean.getBoolean("netbeans.debug.exceptions")) // NOI18N
65
ex.printStackTrace();
66             System.err.println("[WARNING] BeanSupport cannot create default instance of: "+beanClass.getName());
67             return null;
68         }
69     }
70
71
72     /**
73      * Utility method to obtain an instance of specified beanClass. The
74      * instance is reused, and thus should only be used to obtain info about
75      * settings of default instances of the specified class.
76      * @param beanClass the class to create inctance of
77      * @return instance of specified class or null if an error occured during
78      * instantiation
79      */

80     public static Object JavaDoc getDefaultInstance(Class JavaDoc beanClass) {
81         Object JavaDoc defInstance = instancesCache.get(beanClass);
82         if (defInstance == null) {
83             defInstance = createBeanInstance(beanClass);
84             if (defInstance instanceof Component) {
85                 FakePeerSupport.attachFakePeer((Component)defInstance);
86                 if (defInstance instanceof Container)
87                     FakePeerSupport.attachFakePeerRecursively(
88                                                     (Container)defInstance);
89             }
90
91             // hack for JTextField - default background depends on whether
92
// the component is editable or not
93
if (defInstance instanceof javax.swing.JTextField JavaDoc) {
94                 Object JavaDoc[] values = new Object JavaDoc[2];
95                 javax.swing.JTextField JavaDoc jtf = (javax.swing.JTextField JavaDoc) defInstance;
96                 values[0] = jtf.getBackground();
97                 jtf.setEditable(false);
98                 values[1] = jtf.getBackground();
99                 jtf.setEditable(true);
100
101                 Map deviationMap = new HashMap();
102                 deviationMap.put(
103                     "background", // NOI18N
104
new DefaultValueDeviation(values) {
105                         Object JavaDoc getValue(Object JavaDoc beanInstance) {
106                             return ((javax.swing.JTextField JavaDoc)beanInstance).isEditable() ?
107                                    this.values[0] : this.values[1];
108                         }
109                     }
110                 );
111
112                 deviationsCache.put(beanClass, deviationMap);
113             }
114
115             instancesCache.put(beanClass, defInstance);
116         }
117         return defInstance;
118     }
119
120     /**
121      * Utility method to obtain a default property values of specified JavaBean
122      * class. The default values are property values immediately after the
123      * instance is created. Because some AWT components initialize their
124      * properties only after the peer is created, these are treated specially
125      * and default values for those properties are provided
126      * explicitely(e.g. though the value of Font property of java.awt.Button is
127      * null after an instance of Button is created, this method will return the
128      * Font(Dialog, 12, PLAIN) as the default value).
129      *
130      * @param beanClass The Class of the JavaBean for which the default values
131      * are to be obtained
132      * @return Map containing pairs <PropertyName(String), value(Object)>
133      * @see #getDefaultPropertyValue
134      */

135     
136     public static Map getDefaultPropertyValues(Class JavaDoc beanClass) {
137         Map defValues =(Map) valuesCache.get(beanClass);
138         if (defValues == null) {
139             Object JavaDoc beanInstance = getDefaultInstance(beanClass);
140             if (beanInstance == null)
141                 return errorEmptyMap;
142             defValues = getPropertyValues(beanInstance);
143             valuesCache.put(beanClass, defValues);
144         }
145         return defValues;
146     }
147
148     /**
149      * Utility method to obtain a default value of specified JavaBean class and
150      * property name. The default values are property values immediately after
151      * the instance is created. Because some AWT components initialize their
152      * properties only after the peer is created, these are treated specially
153      * and default values for those properties are provided
154      * explicitely(e.g. though the value of Font property of java.awt.Button is
155      * null after an instance of Button is created, this method will return the
156      * Font(Dialog, 12, PLAIN) as the default value).
157      *
158      * @param beanClass The Class of the JavaBean for which the default value
159      * is to be obtained
160      * @param beanClass The name of the propertyn for which the default value
161      * is to be obtained
162      * @return The default property value for specified property on specified
163      * JavaBean class
164      * @see #getDefaultPropertyValues
165      */

166     public static Object JavaDoc getDefaultPropertyValue(Object JavaDoc bean,
167                                                  String JavaDoc propertyName)
168     {
169         Map deviationMap = (Map) deviationsCache.get(bean.getClass());
170         if (deviationMap != null) {
171             DefaultValueDeviation deviation = (DefaultValueDeviation)
172                                               deviationMap.get(propertyName);
173             if (deviation != null)
174                 return deviation.getValue(bean);
175         }
176
177         Map valuesMap = getDefaultPropertyValues(bean.getClass());
178         Object JavaDoc value = valuesMap.get(propertyName);
179         return value != null || valuesMap.containsKey(propertyName) ?
180                value : NO_VALUE;
181     }
182
183     /**
184      * Utility method to obtain a current property values of given JavaBean instance.
185      * Only the properties specified in bean info(if it exists) are provided.
186      *
187      * @return Map containing pairs <PropertyName(String), value(Object)>
188      */

189     public static Map getPropertyValues(Object JavaDoc beanInstance) {
190         if (beanInstance == null) {
191             return errorEmptyMap;
192         }
193
194         BeanInfo info;
195         try {
196             info = FormUtils.getBeanInfo(beanInstance.getClass());
197         } catch (IntrospectionException ex) {
198             return errorEmptyMap;
199         }
200         PropertyDescriptor[] properties = info.getPropertyDescriptors();
201         HashMap defaultValues = new HashMap(properties.length * 2);
202
203         for (int i = 0; i < properties.length; i++) {
204             defaultValues.put(properties[i].getName(), NO_VALUE);
205             
206             Method JavaDoc readMethod = properties[i].getReadMethod();
207             if (readMethod != null) {
208                 try {
209                     Object JavaDoc value = readMethod.invoke(beanInstance, new Object JavaDoc [0]);
210                     defaultValues.put(properties[i].getName(), value);
211                 } catch (Exception JavaDoc e) {
212                 }
213             }
214         }
215
216         return defaultValues;
217     }
218
219     /** Utility method that obtains icon for a bean class.
220      * (This method is currently used only for obtaining default icons for AWT
221      * components. Other icons should be provided by BeanInfo.)
222      */

223     public static Image getBeanIcon(Class JavaDoc beanClass, int iconType) {
224         return getIconForDefault(beanClass);
225     }
226
227     /** A utility method that returns a class of event adapter for
228      * specified listener. It works only on known listeners from java.awt.event.
229      * Null is returned for unknown listeners.
230      * @return class of an adapter for specified listener or null if
231      * unknown/does not exist
232      */

233     public static Class JavaDoc getAdapterForListener(Class JavaDoc listener) {
234         if (java.awt.event.ComponentListener JavaDoc.class.equals(listener))
235             return java.awt.event.ComponentAdapter JavaDoc.class;
236         else if (java.awt.event.ContainerListener JavaDoc.class.equals(listener))
237             return java.awt.event.ContainerAdapter JavaDoc.class;
238         else if (java.awt.event.FocusListener JavaDoc.class.equals(listener))
239             return java.awt.event.FocusAdapter JavaDoc.class;
240         else if (java.awt.event.KeyListener JavaDoc.class.equals(listener))
241             return java.awt.event.KeyAdapter JavaDoc.class;
242         else if (java.awt.event.MouseListener JavaDoc.class.equals(listener))
243             return java.awt.event.MouseAdapter JavaDoc.class;
244         else if (java.awt.event.MouseMotionListener JavaDoc.class.equals(listener))
245             return java.awt.event.MouseMotionAdapter JavaDoc.class;
246         else if (java.awt.event.WindowListener JavaDoc.class.equals(listener))
247             return java.awt.event.WindowAdapter JavaDoc.class;
248         else return null; // not found
249
}
250
251     // -----------------------------------------------------------------------------
252
// Private methods
253

254     static Reference JavaDoc<Map<String JavaDoc,Object JavaDoc>> imageCache;
255
256     private static synchronized Image getIconForDefault(Class JavaDoc klass) {
257         Map<String JavaDoc,Object JavaDoc> icons;
258         if ((imageCache == null) || ((icons = imageCache.get()) == null)) {
259             icons = createImageCache();
260             imageCache = new SoftReference JavaDoc<Map<String JavaDoc,Object JavaDoc>>(icons);
261         }
262         
263         String JavaDoc name = klass.getName();
264         Object JavaDoc img = icons.get(name);
265         
266         if (img == null) {
267             return null;
268         }
269         
270         if (img instanceof Image) {
271             return (Image) img;
272         } else {
273             Image image = Utilities.loadImage((String JavaDoc)img);
274             icons.put(name, image);
275             return image;
276         }
277     }
278
279     private static Map<String JavaDoc, Object JavaDoc> createImageCache() {
280         Map<String JavaDoc, Object JavaDoc> map = new HashMap<String JavaDoc, Object JavaDoc>();
281         
282         map.put("java.awt.Label", "org/netbeans/modules/form/beaninfo/awt/label.gif"); // NOI18N
283
map.put("java.awt.Button", "org/netbeans/modules/form/beaninfo/awt/button.gif"); // NOI18N
284
map.put("java.awt.TextField", "org/netbeans/modules/form/beaninfo/awt/textfield.gif"); // NOI18N
285
map.put("java.awt.TextArea", "org/netbeans/modules/form/beaninfo/awt/textarea.gif"); // NOI18N
286
map.put("java.awt.Checkbox", "org/netbeans/modules/form/beaninfo/awt/checkbox.gif"); // NOI18N
287
map.put("java.awt.Choice", "org/netbeans/modules/form/beaninfo/awt/choice.gif"); // NOI18N
288
map.put("java.awt.List", "org/netbeans/modules/form/beaninfo/awt/list.gif"); // NOI18N
289
map.put("java.awt.Scrollbar", "org/netbeans/modules/form/beaninfo/awt/scrollbar.gif"); // NOI18N
290
map.put("java.awt.ScrollPane", "org/netbeans/modules/form/beaninfo/awt/scrollpane.gif"); // NOI18N
291
map.put("java.awt.Panel", "org/netbeans/modules/form/beaninfo/awt/panel.gif"); // NOI18N
292
map.put("java.awt.Canvas", "org/netbeans/modules/form/beaninfo/awt/canvas.gif"); // NOI18N
293
map.put("java.awt.MenuBar", "org/netbeans/modules/form/beaninfo/awt/menubar.gif"); // NOI18N
294
map.put("java.awt.PopupMenu", "org/netbeans/modules/form/beaninfo/awt/popupmenu.gif"); // NOI18N
295
map.put("java.awt.Menu", "org/netbeans/modules/form/resources/menu.gif"); // NOI18N
296
map.put("java.awt.MenuItem", "org/netbeans/modules/form/resources/menuItem.gif"); // NOI18N
297
map.put("java.awt.CheckboxMenuItem", "org/netbeans/modules/form/resources/menuItemCheckbox.gif"); // NOI18N
298
map.put("org.netbeans.modulres.form.Separator", "org/netbeans/modules/form/resources/menuSeparator.gif"); // NOI18N
299

300         map.put("java.applet.Applet", "org/netbeans/modules/form/resources/applet.gif"); // NOI18N
301
map.put("java.awt.Dialog", "org/netbeans/modules/form/resources/dialog.gif"); // NOI18N
302
map.put("java.awt.Frame", "org/netbeans/modules/form/resources/frame.gif"); // NOI18N
303

304         return map;
305     }
306
307     private static abstract class DefaultValueDeviation {
308         protected Object JavaDoc[] values;
309         DefaultValueDeviation(Object JavaDoc[] values) {
310             this.values = values;
311         }
312         abstract Object JavaDoc getValue(Object JavaDoc beanInstance);
313     }
314 }
315
Popular Tags