KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > text > template > BeanDataHandler


1 /***************************************************************************
2  * Copyright 2001-2003 The eXo Platform SARL All rights reserved. *
3  * Please look at license.txt in info directory for more license detail. *
4  **************************************************************************/

5 package org.exoplatform.text.template;
6
7 import java.util.* ;
8 import net.sf.cglib.reflect.FastClass;
9 /**
10  * @author Tuan Nguyen (tuan08@users.sourceforge.net)
11  * @since Feb 1, 2005
12  * @version $Id$
13  */

14 public class BeanDataHandler implements DataHandler {
15   private static Class JavaDoc[] EMPTY_TYPE = {} ;
16   private static Object JavaDoc[] EMPTY_ARGS = {} ;
17   private static Map fastClassMap_ = new HashMap(300) ;
18   
19   private Object JavaDoc bean_ ;
20   private FastClass fastClass_ ;
21   private Class JavaDoc type_ ;
22   
23   public BeanDataHandler(Class JavaDoc beanType) {
24     type_ = beanType ;
25     fastClass_ = getFastClass(beanType) ;
26   }
27   
28   public BeanDataHandler(Object JavaDoc bean) {
29     bean_ = bean ;
30     type_ = bean.getClass() ;
31     fastClass_ = getFastClass(type_);
32   }
33   
34   public Class JavaDoc getDataTypeHandler() { return type_ ; }
35   
36   public String JavaDoc getValueAsString(DataBindingValue value) {
37     try {
38       Object JavaDoc o = fastClass_.invoke(value.getMethodName(), EMPTY_TYPE, bean_, EMPTY_ARGS) ;
39       if(o == null) return "" ;
40       return o.toString();
41     } catch (Exception JavaDoc ex) {
42       return value.getExpression() + " has error: " + ex.getMessage();
43     }
44   }
45   
46   public Object JavaDoc getValue(DataBindingValue value) {
47     try {
48       Object JavaDoc o = fastClass_.invoke(value.getMethodName(), EMPTY_TYPE, bean_, EMPTY_ARGS) ;
49       return o;
50     } catch (Exception JavaDoc ex) {
51       return value.getExpression() + " has error: " + ex.getMessage();
52     }
53   }
54   
55   public void setBean(Object JavaDoc bean) {
56     bean_ = bean ;
57   }
58   
59   private FastClass getFastClass(Class JavaDoc type) {
60     FastClass fc = (FastClass)fastClassMap_.get(type) ;
61     if(fc == null) {
62       synchronized(fastClassMap_) {
63         fc = FastClass.create(type) ;
64         fastClassMap_.put(type, fc) ;
65       }
66     }
67     return fc ;
68   }
69 }
70
Popular Tags