KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > bsf > engines > activescript > JavaBean


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2002 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "Apache BSF", "Apache", and "Apache Software Foundation"
27  * must not be used to endorse or promote products derived from
28  * this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many individuals
50  * on behalf of the Apache Software Foundation and was originally created by
51  * Sanjiva Weerawarana and others at International Business Machines
52  * Corporation. For more information on the Apache Software Foundation,
53  * please see <http://www.apache.org/>.
54  */

55
56 package org.apache.bsf.engines.activescript;
57
58 import java.util.Vector JavaDoc;
59 import java.lang.reflect.*;
60 import java.beans.*;
61
62 import org.apache.bsf.*;
63 import org.apache.bsf.util.*;
64
65 public final class JavaBean {
66
67
68   private static Vector JavaDoc lsMembers = new Vector JavaDoc(512, 512);
69   static
70   {
71     lsMembers.addElement(""); //don't use entry 0. It is used to indicate an error.
72
}
73    
74   private static final short DISPATCH_METHOD= 0x01;
75   private static final short DISPATCH_PROPERTYGET = 0x02;
76   private static final short DISPATCH_PROPERTYPUT= 0x04;
77   private static final short DISPATCH_PROPERTYPUTREF= 0x08;
78   private static final short DISPATCH_CASESENSITIVE= 0x40;
79   private static final short DISPATCH_THROWEXCEPTION= 0x80;
80   
81
82   /**
83    * Bind the member to a unique index. Use positive indexes for methods,
84    * negative indexes for properties. Matches are case insensitive
85    * Convenience fuction for those engines not knowing dispatch type, case insensitive, and not wanting exception
86    */

87   
88    public final static int bindMember(Class JavaDoc jclass, String JavaDoc name) throws Exception JavaDoc {
89       return bindMember( jclass, name, (short)( DISPATCH_PROPERTYGET | DISPATCH_PROPERTYPUT | DISPATCH_METHOD ));
90    }
91   /**
92    * Bind the member to a unique index. Use positive indexes for methods,
93    * negative indexes for properties. Matches are case insensitive.
94    */

95
96    public final static int bindMember(Class JavaDoc jclass, String JavaDoc name, short bindType) throws Exception JavaDoc {
97     /* See if there is a unique match on method names, ignoring case.
98      * There are four cases to consider:
99      * 1) no methods match: Match remains null.
100      * 2) only one method matches: Match is the unique method
101      * 3) multiple matches, with all names matching exactly:
102      * Match is of type String with a value of the name
103      * 4) multiple matches, differing in case:
104      * return from method with a result of zero, indicating no match
105      */

106     Object JavaDoc match = null;
107
108     boolean throwException = 0 != (bindType & DISPATCH_THROWEXCEPTION);
109     boolean respectCase = 0 != (bindType & DISPATCH_CASESENSITIVE);
110     boolean dispatchMethod= (0!=(bindType & DISPATCH_METHOD));
111     boolean dispatchPropertyGet= (0!=(bindType & DISPATCH_PROPERTYGET));
112     boolean dispatchPropertyPut= (0!=(bindType & DISPATCH_PROPERTYPUT)) ||(0!=(bindType & DISPATCH_PROPERTYPUTREF));
113    
114     if(!( dispatchMethod || dispatchPropertyGet || dispatchPropertyPut )) dispatchMethod= dispatchPropertyGet= dispatchPropertyPut= true;
115
116
117     Method jmethods[] = jclass.getMethods();
118
119     for (int i=0; i<jmethods.length; i++) {
120
121       if (respectCase ?jmethods[i].getName().equals(name):jmethods[i].getName().equalsIgnoreCase(name) ) {
122
123         if (match == null) {
124           // first match
125
match = jmethods[i];
126
127         } else if (match instanceof Method) {
128
129           if (jmethods[i].getName().equals(((Method)match).getName())) {
130             // second match, but name matches exactly
131
match = jmethods[i].getName();
132             if(respectCase) i= jmethods.length; //in this case we're done just remember the name.
133
} else {
134             if(!respectCase)
135             {
136               // difference in case of names, bail
137
if(throwException)
138                throw new BSFException (BSFException.REASON_OTHER_ERROR,
139                             "Method:" + name + " in " + jclass + "differs between two methods in case only, can't distiguish");
140              return 0;
141             }
142           }
143
144         } else if (!jmethods[i].getName().equals((String JavaDoc)match)) {
145          if(!respectCase)
146          {
147            // difference in case of names, bail
148
if(throwException)
149                throw new BSFException (BSFException.REASON_OTHER_ERROR,
150                             "Method:" + name + " in " + jclass + "differs between two methods in case only, can't distiguish");
151            return 0;
152           }
153         }
154
155       }
156
157     }
158
159     // if there was a match, return the method information
160
if (match != null) {
161       lsMembers.addElement(match);
162       return lsMembers.size()-1;
163     }
164
165     if(!(dispatchPropertyPut || dispatchPropertyGet))
166     {
167       if(throwException)
168         throw new BSFException (BSFException.REASON_OTHER_ERROR,
169                 "Method:" + name + " in " + jclass + "not found.");
170
171       return 0; //done/
172
}
173       
174
175     
176     BeanInfo beanInfo=null ;
177     if(dispatchPropertyPut || dispatchPropertyGet)
178     {
179       // look for bean property information, again looking for a unique match
180
// this case is simpler: there is no overloading, so if two properties
181
// match, they must differ in case.
182
Field jfields[] = jclass.getFields();
183       for (int i=0; i<jfields.length; i++) {
184         if (respectCase ? jfields[i].getName().equals( name) : jfields[i].getName().equalsIgnoreCase( name) ) {
185           if (match != null)
186             {
187             if(throwException)
188              throw new BSFException (BSFException.REASON_OTHER_ERROR,
189                             "Field:" + name + " in " + jclass + "differs between two fields in case only, can't distinguish");
190                  return 0;
191                 }
192           match = jfields[i];
193       if(respectCase) i= jfields.length; //done there should be no more. I hope!
194
}
195       }
196
197       // if there was a unique match, return the property information
198
if (match != null) {
199         lsMembers.addElement(match);
200         return -(lsMembers.size()-1);
201       }
202
203       // look for bean property information, again looking for a unique match
204
beanInfo = Introspector.getBeanInfo(jclass);
205       PropertyDescriptor properties[] = beanInfo.getPropertyDescriptors();
206       for (int i=0; i<properties.length; i++) {
207         if (respectCase? properties[i].getName().equals(name) : properties[i].getName().equalsIgnoreCase(name)) {
208           if (match != null)
209                 {
210             if(throwException)
211              throw new BSFException (BSFException.REASON_OTHER_ERROR,
212                             "Field:" + name + " in " + jclass + "differs between two fields in case only, can't distinguish");
213                   return 0;
214                 }
215           match = properties[i];
216       if(respectCase) i= properties.length; //done there should be no more. I hope!
217
}
218       }
219
220       // if there was a unique match, return the property information
221
if (match != null) {
222         lsMembers.addElement(match);
223         return -(lsMembers.size()-1);
224       }
225     }//Endif(dispatchPropertyPut || dispatchPropertyGet)
226

227     if(dispatchPropertyPut)
228     {
229       // look for bean event information, again looking for a unique match
230
if (name.length() > 2 && (respectCase ? name.substring(0,2).equals("on"):name.substring(0,2).equalsIgnoreCase("on"))) {
231         String JavaDoc eventName = name.substring(2);
232         EventSetDescriptor events[] = beanInfo.getEventSetDescriptors();
233         for (int i=0; i<events.length; i++) {
234           if (respectCase ? events[i].getName().equals(eventName): events[i].getName().equalsIgnoreCase(eventName)) {
235             if (match != null)
236             {
237               if(throwException)
238                        throw new BSFException (BSFException.REASON_OTHER_ERROR,
239                                 "Event:" + name + " in " + jclass + "differs between two fields in case only, can't distinguish");
240                             
241                return 0;
242             }
243             match = events[i];
244         if(respectCase) i= events.length;
245           }
246         }
247      
248         // if there was a unique match, return the property information
249
if (match != null) {
250         lsMembers.addElement(match);
251         return -(lsMembers.size()-1);
252         }
253       }
254     }
255
256
257    if(throwException)
258       throw new BSFException (BSFException.REASON_OTHER_ERROR,
259                 "No method, property, or event matches " + name + " in " + jclass + ".");
260
261     return 0;
262   }
263   /**
264    * Call a method, property getter, or property setter.
265    * If index > 0 then call simple method.
266    * Else if argc = 0 then call getter
267    * Else call setter
268    */

269   public final static Object JavaDoc callMethod(
270     JavaBeanAddEventListener engine,
271     Object JavaDoc bean,
272     int methodID,
273     Object JavaDoc[] args) throws Exception JavaDoc
274   {
275     Object JavaDoc result = null;
276
277     // call the method
278
if (methodID > 0) {
279       Object JavaDoc member = lsMembers.elementAt(methodID);
280       if (member instanceof Method) {
281
282         try
283         {
284          result=((Method)member).invoke(bean, args);
285     }
286     catch(java.lang.reflect.InvocationTargetException JavaDoc e)
287     {
288       java.lang.Throwable JavaDoc original=e.getTargetException();
289        
290        java.io.StringWriter JavaDoc sw= new java.io.StringWriter JavaDoc();
291        java.io.PrintWriter JavaDoc pw= new java.io.PrintWriter JavaDoc(sw);
292        original.printStackTrace(pw);
293            throw new BSFException (BSFException.REASON_OTHER_ERROR,
294                             "Target method exception(" + original + ") message is: " +original.getMessage() + "stack trace" + sw.toString(), original );
295     }
296       } else {
297         result=EngineUtils.callBeanMethod(bean, (String JavaDoc)member, args);
298       }
299     } else {
300       Object JavaDoc member = lsMembers.elementAt(-methodID);
301       if (member instanceof PropertyDescriptor) {
302         PropertyDescriptor property = (PropertyDescriptor)member;
303         if (args.length>0)
304     {
305       Method method= property.getWriteMethod();
306       
307           if(null== method) throw new BSFException (BSFException.REASON_OTHER_ERROR,
308                 "Property " + property.getName() + " in " + bean.getClass() + " is read only.");
309           result = method.invoke(bean, args);
310     }
311         else
312     {
313       Method method= property.getReadMethod();
314
315           if(null== method) throw new BSFException (BSFException.REASON_OTHER_ERROR,
316                 "Property " + property.getName() + " in " + bean.getClass() + " is write only.");
317
318           result = method.invoke(bean, args);
319     }
320       } else if (member instanceof Field) {
321         Field field = (Field)member;
322         if (args.length>0)
323           field.set(bean, args[0]);
324         else
325           result = field.get(bean);
326       } else {
327         if (args.length>0) {
328           engine.addEventListener(bean,
329             ((EventSetDescriptor)member).getName(), null,
330             args[0].toString());
331         }
332       }
333     }
334
335     return result;
336   }
337 }
338
Popular Tags