KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > nightlabs > util > bean > BeanUtil


1 /* ************************************************************************** *
2  * Copyright (C) 2004 NightLabs GmbH, Marco Schulze *
3  * All rights reserved. *
4  * http://www.NightLabs.de *
5  * *
6  * This program and the accompanying materials are free software; you can re- *
7  * distribute it and/or modify it under the terms of the GNU General Public *
8  * License as published by the Free Software Foundation; either ver 2 of the *
9  * License, or any later version. *
10  * *
11  * This module is distributed in the hope that it will be useful, but WITHOUT *
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FIT- *
13  * NESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more *
14  * details. *
15  * *
16  * You should have received a copy of the GNU General Public License along *
17  * with this module; if not, write to the Free Software Foundation, Inc.: *
18  * 59 Temple Place, Suite 330 *
19  * Boston MA 02111-1307 *
20  * USA *
21  * *
22  * Or get it online: *
23  * http://www.opensource.org/licenses/gpl-license.php *
24  * *
25  * In case, you want to use this module or parts of it in a proprietary pro- *
26  * ject, you can purchase it under the NightLabs Commercial License. Please *
27  * contact NightLabs GmbH under info AT nightlabs DOT com for more infos or *
28  * visit http://www.NightLabs.com *
29  * ************************************************************************** */

30
31 /*
32  * <p> Project: NightLabsBase </p>
33  * <p> Copyright: Copyright (c) 2004 </p>
34  * <p> Company: NightLabs GmbH (Germany) </p>
35  * <p> Creation Date: 13.08.2004 </p>
36  */

37
38 package com.nightlabs.util.bean;
39
40 import java.beans.BeanInfo JavaDoc;
41 import java.beans.IntrospectionException JavaDoc;
42 import java.beans.Introspector JavaDoc;
43 import java.beans.PropertyDescriptor JavaDoc;
44 import java.lang.reflect.Method JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Vector JavaDoc;
50
51 import com.nightlabs.util.bean.propertyeditor.PropertyEditorUI;
52 import com.nightlabs.util.bean.propertyeditor.PropertyEditorUIException;
53
54 public class BeanUtil
55 {
56     public static final int USE_ALL_BEANINFO = Introspector.USE_ALL_BEANINFO;
57     public static final int IGNORE_ALL_BEANINFO = Introspector.IGNORE_ALL_BEANINFO;
58     public static final int IGNORE_IMMEDIATE_BEANINFO = Introspector.IGNORE_IMMEDIATE_BEANINFO;
59     
60     public BeanUtil(int mode)
61     {
62         if (mode != USE_ALL_BEANINFO &&
63                 mode != IGNORE_ALL_BEANINFO &&
64                 mode != IGNORE_IMMEDIATE_BEANINFO)
65             throw new IllegalArgumentException JavaDoc("Param mode is neither USE_ALL_BEANINFO nor IGNORE_ALL_BEANINFO nor IGNORE_IMMEDIATE_BEANINFO!");
66             
67         this.currentMode = mode;
68     }
69     
70     /**
71      * This int determines the Mode by which the Introspector should
72      * search for BeanInfo-Files
73      *
74      * @see #USE_ALL_BEANINFO
75      * @see #IGNORE_ALL_BEANINFO
76      * @see #IGNORE_IMMEDIATE_BEANINFO
77      *
78      * @see java.beans.Introspector
79      */

80     protected int currentMode = USE_ALL_BEANINFO;
81     public int getCurrentMode() {
82         return currentMode;
83     }
84     public void setCurrentMode(int mode) {
85         currentMode = mode;
86     }
87         
88     /**
89      * Collects all Methods (java.lang.reflect.Method) for the
90      * given beanClass (java.lang.Class)
91      *
92      * @param beanClass The beanClass for which all Methods are collected
93      * @return a List of Method[] which contains the the get/Read-Method
94      * as Method[0] and the set/Write-Method as Method[1]
95      *
96      */

97     public static List JavaDoc getBeanMethods(Class JavaDoc beanClass, int flag)
98     throws IntrospectionException JavaDoc
99     {
100         Vector JavaDoc propertyMethods = new Vector JavaDoc();
101         BeanInfo JavaDoc beanInfo = Introspector.getBeanInfo(beanClass, flag);
102         PropertyDescriptor JavaDoc[] pds = beanInfo.getPropertyDescriptors();
103         propertyMethods = new Vector JavaDoc(pds.length);
104         for (int i=0; i < pds.length; i++)
105         {
106             Method JavaDoc[] methods = new Method JavaDoc[2];
107             PropertyDescriptor JavaDoc pd = pds[i];
108             methods[0] = pd.getReadMethod();
109             methods[1] = pd.getWriteMethod();
110             propertyMethods.add(methods);
111         }
112         return propertyMethods;
113     }
114
115     /**
116      * Collects all Methods (java.lang.reflect.Method) for the
117      * given beanClass (java.lang.Class)
118      *
119      * @param beanClass The beanClass for which all Methods are collected
120      * @return a List of Method[] which contains the the get/Read-Method
121      * as Method[0] and the set/Write-Method as Method[1]
122      *
123      */

124     public static List JavaDoc getBeanMethods(Class JavaDoc beanClass, Class JavaDoc stopClass)
125     throws IntrospectionException JavaDoc
126     {
127         Vector JavaDoc propertyMethods = new Vector JavaDoc();
128         BeanInfo JavaDoc beanInfo = Introspector.getBeanInfo(beanClass, stopClass);
129         PropertyDescriptor JavaDoc[] pds = beanInfo.getPropertyDescriptors();
130         propertyMethods = new Vector JavaDoc(pds.length);
131         for (int i=0; i < pds.length; i++)
132         {
133             Method JavaDoc[] methods = new Method JavaDoc[2];
134             PropertyDescriptor JavaDoc pd = pds[i];
135             methods[0] = pd.getReadMethod();
136             methods[1] = pd.getWriteMethod();
137             propertyMethods.add(methods);
138         }
139         return propertyMethods;
140     }
141     
142     
143     /**
144      * @param beanClass the Class of the bean
145      * @param flag IGNORE_ALL_BEANINFO,
146      * IGNORE_IMMEDIATE_BEANINFO,
147      * USE_ALL_BEANINFO
148      * @return an PropertyDescriptor[] of all PropertyDescrptors for this certain beanClass and the corresponding flag
149      * @throws IntrospectionException
150      * @see java.lang.reflect.PropertyDescriptor
151      * @see java.lang.reflect.Introspector
152      */

153     public static PropertyDescriptor JavaDoc[] getPropertyDescriptors(Class JavaDoc beanClass, int flag)
154     throws IntrospectionException JavaDoc
155     {
156         BeanInfo JavaDoc beanInfo = Introspector.getBeanInfo(beanClass, flag);
157         return beanInfo.getPropertyDescriptors();
158     }
159
160     /**
161      * @param beanClass the Class of the bean
162      * @param flag IGNORE_ALL_BEANINFO,
163      * IGNORE_IMMEDIATE_BEANINFO,
164      * USE_ALL_BEANINFO
165      * @return a List of all PropertyDescriptors for the specific beanClass
166      * @throws IntrospectionException
167      * @see java.lang.reflect.Introspector
168      */

169     public static List JavaDoc getPropertyDescriptorsAsVector(Class JavaDoc beanClass, int flag)
170     throws IntrospectionException JavaDoc
171     {
172         BeanInfo JavaDoc beanInfo = Introspector.getBeanInfo(beanClass, flag);
173         PropertyDescriptor JavaDoc[] pdsArray = beanInfo.getPropertyDescriptors();
174         Vector JavaDoc pdsVector = new Vector JavaDoc(pdsArray.length);
175         for (int i=0; i < pdsArray.length; i++)
176         {
177           pdsVector.add(pdsArray[i]);
178         }
179         return pdsVector;
180     }
181
182     public Map JavaDoc getProperty2Bean2Pd(List JavaDoc beans)
183     throws IntrospectionException JavaDoc
184     {
185         List JavaDoc oldProperties = null;
186         List JavaDoc oldPropertyNames = new Vector JavaDoc();
187         Map JavaDoc property2Bean2Pd = new HashMap JavaDoc();
188         
189         for (Iterator JavaDoc it = beans.iterator(); it.hasNext(); )
190         {
191             Object JavaDoc bean = it.next();
192             List JavaDoc pds = getPropertyDescriptorsAsVector(bean.getClass(), getCurrentMode());
193             // if this is the first row copy all PropertyDescriptors(PDs) of the
194
// first bean in the oldProperties Vector and put the propertyNames
195
// in a seperate Vector because of quicker comparison (contains)
196
if (oldProperties == null)
197             {
198                 oldProperties = pds;
199                 for (Iterator JavaDoc it2 = oldProperties.iterator(); it2.hasNext(); )
200                 {
201                     PropertyDescriptor JavaDoc pd = (PropertyDescriptor JavaDoc) it2.next();
202                     String JavaDoc propertyName = pd.getName();
203                     oldPropertyNames.add(propertyName);
204                     HashMap JavaDoc bean2pd = new HashMap JavaDoc();
205                     bean2pd.put(bean, pd);
206                     property2Bean2Pd.put(propertyName, bean2pd);
207                 } // for (Iterator it2 = oldProperties.iterator(); it2.hasNext(); )
208
} // if (oldProperties == null)
209

210             // otherwise compare the new PDs with the oldProperties
211
// and remove not equal properties
212
else // if (oldProperties == null)
213
{
214                 for (Iterator JavaDoc it2 = pds.iterator(); it2.hasNext(); )
215                 {
216                     PropertyDescriptor JavaDoc newPD = (PropertyDescriptor JavaDoc) it2.next();
217                     String JavaDoc newProperyName = newPD.getName();
218                     // if this bean has the same property add it to
219
// ClassesVector in the corresponding HashMap
220
if (oldPropertyNames.contains(newProperyName))
221                     {
222                         HashMap JavaDoc bean2pd = (HashMap JavaDoc) property2Bean2Pd.get(newProperyName);
223                         bean2pd.put(bean, newPD);
224                     }
225                     // otherwise remove it from the HashMap and the Vector
226
else {
227                         property2Bean2Pd.remove(newProperyName);
228                         oldPropertyNames.remove(newProperyName);
229                     }
230                 }
231             } // else // if (oldProperties.isEmpty())
232
} // for (Iterator it = beans.iterator(); it.hasNext(); )
233
return property2Bean2Pd;
234     }
235     
236     /**
237      * Checks if all beans in the Vector are a Instance of the same Class
238      * @param beans a List of beans
239      * @return the Class if all beans are a Instance from the same Class
240      * null if not all beans are a Instance from the same Class
241      */

242     public static Class JavaDoc getAllBeansSingleClass(List JavaDoc beans)
243     {
244         // first check if all beans are a Instance from the same class
245
Class JavaDoc firstClass = null;
246         boolean sameClass = true;
247         for (Iterator JavaDoc it = beans.iterator(); it.hasNext(); )
248         {
249             Object JavaDoc bean = it.next();
250             Class JavaDoc beanClass = bean.getClass();
251             if (firstClass == null) {
252                 firstClass = beanClass;
253             }
254             if(!firstClass.equals(beanClass)) {
255                 sameClass = false;
256                 break;
257             }
258         }
259         return sameClass ? firstClass : null;
260     }
261     
262     public List JavaDoc getSamePropertyDescriptors(List JavaDoc beans)
263     throws IntrospectionException JavaDoc
264     {
265         List JavaDoc oldPropertyDescriptors = null;
266         List JavaDoc classes = new Vector JavaDoc();
267
268         for (Iterator JavaDoc it = beans.iterator(); it.hasNext(); )
269         {
270             Object JavaDoc bean = it.next();
271             List JavaDoc pds = getPropertyDescriptorsAsVector(bean.getClass(), currentMode);
272             
273             // if this is the first row copy all PropertyDescriptors(PDs) of the
274
// first bean in the oldPropertyDescriptors Vector
275
// additionally save the beanClass and the corresponding PropertyDescriptors,
276
// to avoid catching the PDs for another bean of the same class
277
if (oldPropertyDescriptors == null)
278             {
279                 oldPropertyDescriptors = pds;
280                 classes.add(bean.getClass());
281             } // if (oldProperties == null)
282

283             // otherwise compare the new PDs with the oldProperties
284
// and remove not equal properties
285
else // if (oldPropertyDescriptors == null)
286
{
287                 if (classes.contains(bean.getClass()))
288                 {
289                     continue;
290                 }
291                 else // if (class2Beans.keySet().contains(bean.getClass()))
292
{
293                     classes.add(bean.getClass());
294                     Vector JavaDoc indexes = new Vector JavaDoc();
295                     for (int i=oldPropertyDescriptors.size()-1; i>=0; i--)
296                     {
297                         PropertyDescriptor JavaDoc oldPD = (PropertyDescriptor JavaDoc)oldPropertyDescriptors.get(i);
298                         if (pds.contains(oldPD)) {
299                             continue;
300                         }
301                         else {
302                             indexes.add(new Integer JavaDoc(i));
303                         }
304                     } // for (Iterator it2 = oldPropertyDescriptors.iterator(); it2.hasNext(); )
305
if (!indexes.isEmpty())
306                     {
307                         for (Iterator JavaDoc itIndex = indexes.iterator(); itIndex.hasNext(); ) {
308                             int index = ((Integer JavaDoc) itIndex.next()).intValue();
309                             oldPropertyDescriptors.remove(index);
310                         }
311                     }
312                         
313                 } // else // if (class2Beans.keySet().contains(bean.getClass()))
314
} // else // if (oldPropertyDescriptors == null)
315

316         } // for (Iterator it = beans.iterator(); it.hasNext(); )
317
return oldPropertyDescriptors;
318     } // public HashMap getSamePropertyDescriptors(Vector beans)
319

320     /**
321      *
322      * @param _propertyDescriptors A List of PropertyDescriptors
323      * @return A List of PropertyEditorUIs for the Parameter _propertyDescriptors
324      *
325      * @see java.beans.PropertyDescriptor
326      * @see com.nightlabs.editor2d.shared.drawcomponents.propertyeditors.PropertyEditorUI
327      */

328     public List JavaDoc getPropertyEditorUIsFromPDs(List JavaDoc _propertyDescriptors)
329     {
330         Vector JavaDoc editorUIs = new Vector JavaDoc();
331         for (Iterator JavaDoc it = _propertyDescriptors.iterator(); it.hasNext(); )
332         {
333             PropertyDescriptor JavaDoc pd = (PropertyDescriptor JavaDoc) it.next();
334             if (pd == null) {
335                 continue;
336             }
337             PropertyEditorUI editorUI = new PropertyEditorUI(pd);
338             editorUIs.addElement(editorUI);
339         }
340         return editorUIs;
341     }
342     
343     /**
344      * This Method returns all PropertyEditorUIs for a certain amount of beans
345      *
346      * @param _beans A List of targetBeans
347      * @return A List of PropertyEditorUIs which all target beans of the
348      * Parameter _beans share
349      * @throws IntrospectionException
350      */

351     public List JavaDoc getPropertyEditorUIsFromBeans(List JavaDoc _beans)
352     throws IntrospectionException JavaDoc
353     {
354         Class JavaDoc classForAllBeans = getAllBeansSingleClass(_beans);
355         if (classForAllBeans != null)
356         {
357             List JavaDoc pds = getPropertyDescriptorsAsVector(classForAllBeans, getCurrentMode());
358             List JavaDoc editorUIs = getPropertyEditorUIsFromPDs(pds);
359             return editorUIs;
360         }
361         else {
362             List JavaDoc pds = getSamePropertyDescriptors(_beans);
363             List JavaDoc editorUIs = getPropertyEditorUIsFromPDs(pds);
364             return editorUIs;
365         }
366     }
367
368     
369     /**
370      * @return the property name for a given set method
371      * @param methodName method name. If the name is not the one of a set or get method
372      * name, the result is not guaranteed.
373      */

374     public static String JavaDoc getPropertyName(String JavaDoc methodName, boolean spaces)
375     {
376         String JavaDoc propertyName = "";
377         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(methodName);
378         if (sb.substring(0,3).equals("get") ||
379                 sb.substring(0,3).equals("set"))
380         {
381             propertyName = methodName.substring(3);
382         }
383         else if (sb.substring(0,2).equals("is")) {
384             propertyName = methodName.substring(2);
385         }
386
387         if (spaces)
388         {
389             // Now, parse name and look for upper case letter
390
// A space is inserted in front of each upper case letter
391
// to get a more user friendly name
392
char buff[] = propertyName.toCharArray();
393             int n = buff != null ? buff.length : 0;
394             char data[] = new char[n * 2];
395             int j = 1;
396             data[0] = buff[0];
397             for (int i = 1; i < n; i++) {
398                 char c = buff[i];
399                 if (Character.isUpperCase(c))
400                     data[j++] = ' ';
401                 data[j++] = c;
402             }
403             
404             return new String JavaDoc(data, 0, j);
405         }
406         return propertyName;
407     }
408     
409     public Object JavaDoc getValue(Object JavaDoc bean, String JavaDoc propertyName)
410     {
411         try {
412             BeanInfo JavaDoc bi = Introspector.getBeanInfo(bean.getClass(), currentMode);
413             PropertyDescriptor JavaDoc[] pds = bi.getPropertyDescriptors();
414             for (int i=0; i<pds.length; i++) {
415                 PropertyDescriptor JavaDoc pd = pds[i];
416                 if (pd.getName().equals(propertyName))
417                     return pd.getValue(propertyName);
418             }
419         } catch (IntrospectionException JavaDoc e) {
420             e.printStackTrace();
421         }
422         return null;
423     }
424
425     public void setValue(Object JavaDoc bean, String JavaDoc propertyName)
426     {
427         try {
428             BeanInfo JavaDoc bi = Introspector.getBeanInfo(bean.getClass(), currentMode);
429             PropertyDescriptor JavaDoc[] pds = bi.getPropertyDescriptors();
430             for (int i=0; i<pds.length; i++) {
431                 PropertyDescriptor JavaDoc pd = pds[i];
432                 if (pd.getName().equals(propertyName))
433                     pd.setValue(propertyName, bean);
434             }
435         } catch (IntrospectionException JavaDoc e) {
436             e.printStackTrace();
437         }
438     }
439     
440     
441     /**
442      * Sets the UI components with values reflecting the beans state
443      */

444     public void loadUIValues(List JavaDoc _editorUIs, List JavaDoc _beans)
445     throws PropertyEditorUIException
446     {
447         for (Iterator JavaDoc it = _editorUIs.iterator(); it.hasNext(); )
448         {
449             PropertyEditorUI editorUI = (PropertyEditorUI) it.next();
450             editorUI.load(_beans);
451         }
452     }
453
454     /**
455      * Sets the UI components with values reflecting the beans state
456      */

457     public void loadUIValues(List JavaDoc _editorUIs, Object JavaDoc _bean)
458     throws PropertyEditorUIException
459     {
460         for (Iterator JavaDoc it = _editorUIs.iterator(); it.hasNext(); )
461         {
462             PropertyEditorUI editorUI = (PropertyEditorUI) it.next();
463             editorUI.load(_bean);
464         }
465     }
466
467     /**
468      * Save the value displayed by the UI components into all
469      * beans in the beans Vector
470      */

471     public void saveUIValues(List JavaDoc _editorUIs, List JavaDoc _beans)
472     throws PropertyEditorUIException
473     {
474         for (Iterator JavaDoc it = _editorUIs.iterator(); it.hasNext(); )
475         {
476             PropertyEditorUI editorUI = (PropertyEditorUI) it.next();
477             editorUI.save(_beans);
478         }
479     }
480     
481     /**
482      * Save the value displayed by the UI components into
483      * the single bean Object
484      */

485     public void saveUIValues(List JavaDoc _editorUIs, Object JavaDoc _bean)
486     throws PropertyEditorUIException
487     {
488         for (Iterator JavaDoc it = _editorUIs.iterator(); it.hasNext(); )
489         {
490             PropertyEditorUI editorUI = (PropertyEditorUI) it.next();
491             editorUI.save(_bean);
492         }
493     }
494
495     /**
496      * @param _propertyName The name of the property
497      * @param _beans The List of target beans
498      * @return A Map with a bean as key and the corresponding
499      * PropertyDescriptor as value
500      * @throws IntrospectionException
501      */

502     public Map JavaDoc getPropertyDescriptors(String JavaDoc _propertyName, List JavaDoc _beans)
503     throws IntrospectionException JavaDoc
504     {
505         Map JavaDoc bean2Pd = new HashMap JavaDoc();
506         for (Iterator JavaDoc itBean = _beans.iterator(); itBean.hasNext(); )
507         {
508             Object JavaDoc bean = itBean.next();
509             PropertyDescriptor JavaDoc[] pds = getPropertyDescriptors(bean.getClass(), currentMode);
510             for (int i=0; i < pds.length; i++)
511             {
512                 PropertyDescriptor JavaDoc pd = (PropertyDescriptor JavaDoc) pds[i];
513                 if (pd.getName().equals(_propertyName))
514                 {
515                     bean2Pd.put(bean, pd);
516                 } // if (pd.getName().equals(_propertyName))
517
} // for (int i=0; i < pds.length; i++)
518
} // for (Iterator itBean = _beans.iterator(); itBean.hasNext(); )
519
return bean2Pd;
520     }
521
522     /**
523      * @param _propertyName The name of the property
524      * @param _beans A List of target beans
525      * @return A Map with a bean as key and the corresponding
526      * PropertyEditorUI as value
527      * @throws IntrospectionException
528      */

529     public Map JavaDoc getPropertyEditorUI(String JavaDoc _propertyName, List JavaDoc _beans)
530     throws IntrospectionException JavaDoc
531     {
532         Map JavaDoc bean2EditorUI = new HashMap JavaDoc();
533         for (Iterator JavaDoc itBean = _beans.iterator(); itBean.hasNext(); )
534         {
535             Object JavaDoc bean = itBean.next();
536             PropertyDescriptor JavaDoc[] pds = getPropertyDescriptors(bean.getClass(), currentMode);
537             for (int i=0; i < pds.length; i++)
538             {
539                 PropertyDescriptor JavaDoc pd = (PropertyDescriptor JavaDoc) pds[i];
540                 if (pd.getName().equals(_propertyName))
541                 {
542                     PropertyEditorUI editorUI = new PropertyEditorUI(pd);
543                     bean2EditorUI.put(bean, editorUI);
544                 } // if (pd.getName().equals(_propertyName))
545
} // for (int i=0; i < pds.length; i++)
546
} // for (Iterator itBean = _beans.iterator(); itBean.hasNext(); )
547
return bean2EditorUI;
548     }
549     
550 }
551
Popular Tags