001    /*****************************************************************************
002     *                                                                           *
003     *  This file is part of the BeanShell Java Scripting distribution.          *
004     *  Documentation and updates may be found at http://www.beanshell.org/      *
005     *                                                                           *
006     *  Sun Public License Notice:                                               *
007     *                                                                           *
008     *  The contents of this file are subject to the Sun Public License Version  *
009     *  1.0 (the "License"); you may not use this file except in compliance with *
010     *  the License. A copy of the License is available at http://www.sun.com    * 
011     *                                                                           *
012     *  The Original Code is BeanShell. The Initial Developer of the Original    *
013     *  Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright     *
014     *  (C) 2000.  All Rights Reserved.                                          *
015     *                                                                           *
016     *  GNU Public License Notice:                                               *
017     *                                                                           *
018     *  Alternatively, the contents of this file may be used under the terms of  *
019     *  the GNU Lesser General Public License (the "LGPL"), in which case the    *
020     *  provisions of LGPL are applicable instead of those above. If you wish to *
021     *  allow use of your version of this file only under the  terms of the LGPL *
022     *  and not to allow others to use your version of this file under the SPL,  *
023     *  indicate your decision by deleting the provisions above and replace      *
024     *  them with the notice and other provisions required by the LGPL.  If you  *
025     *  do not delete the provisions above, a recipient may use your version of  *
026     *  this file under either the SPL or the LGPL.                              *
027     *                                                                           *
028     *  Patrick Niemeyer (pat@pat.net)                                           *
029     *  Author of Learning Java, O'Reilly & Associates                           *
030     *  http://www.pat.net/~pat/                                                 *
031     *                                                                           *
032     *****************************************************************************/
033    
034    
035    package bsh;
036    
037    import java.lang.reflect.*;
038    import java.lang.reflect.InvocationHandler;
039    import java.io.*;
040    import java.util.Hashtable;
041    
042    /**
043            XThis is a dynamically loaded extension which extends This.java and adds 
044            support for the generalized interface proxy mechanism introduced in 
045            JDK1.3.  XThis allows bsh scripted objects to implement arbitrary 
046            interfaces (be arbitrary event listener types).
047    
048            Note: This module relies on new features of JDK1.3 and will not compile
049            with JDK1.2 or lower.  For those environments simply do not compile this
050            class.
051    
052            Eventually XThis should become simply This, but for backward compatability
053            we will maintain This without requiring support for the proxy mechanism.
054    
055            XThis stands for "eXtended This" (I had to call it something).
056            
057            @see JThis       See also JThis with explicit JFC support for compatability.
058            @see This       
059    */
060    public class XThis extends This 
061            {
062            /**
063                    A cache of proxy interface handlers.
064                    Currently just one per interface.
065            */
066            Hashtable interfaces;
067    
068            InvocationHandler invocationHandler = new Handler();
069    
070            public XThis( NameSpace namespace, Interpreter declaringInterp ) { 
071                    super( namespace, declaringInterp ); 
072            }
073    
074            public String toString() {
075                    return "'this' reference (XThis) to Bsh object: " + namespace;
076            }
077    
078            /**
079                    Get dynamic proxy for interface, caching those it creates.
080            */
081            public Object getInterface( Class clas ) 
082            {
083                    return getInterface( new Class[] { clas } );
084            }
085    
086            /**
087                    Get dynamic proxy for interface, caching those it creates.
088            */
089            public Object getInterface( Class [] ca ) 
090            {
091                    if ( interfaces == null )
092                            interfaces = new Hashtable();
093    
094                    // Make a hash of the interface hashcodes in order to cache them
095                    int hash = 21;
096                    for(int i=0; i<ca.length; i++)
097                            hash *= ca[i].hashCode() + 3;
098                    Object hashKey = new Integer(hash);
099    
100                    Object interf = interfaces.get( hashKey );
101    
102                    if ( interf == null ) 
103                    {
104                            ClassLoader classLoader = ca[0].getClassLoader(); // ?
105                            interf = Proxy.newProxyInstance( 
106                                    classLoader, ca, invocationHandler );
107                            interfaces.put( hashKey, interf );
108                    }
109    
110                    return interf;
111            }
112    
113            /**
114                    This is the invocation handler for the dynamic proxy.
115                    <p>
116    
117                    Notes:
118                    Inner class for the invocation handler seems to shield this unavailable
119                    interface from JDK1.2 VM...  
120                    
121                    I don't understand this.  JThis works just fine even if those
122                    classes aren't there (doesn't it?)  This class shouldn't be loaded
123                    if an XThis isn't instantiated in NameSpace.java, should it?
124            */
125            class Handler implements InvocationHandler, java.io.Serializable 
126            {
127                    public Object invoke( Object proxy, Method method, Object[] args ) 
128                            throws Throwable
129                    {
130                            try { 
131                                    return invokeImpl( proxy, method, args );
132                            } catch ( TargetError te ) {
133                                    // Unwrap target exception.  If the interface declares that 
134                                    // it throws the ex it will be delivered.  If not it will be 
135                                    // wrapped in an UndeclaredThrowable
136                                    throw te.getTarget();
137                            } catch ( EvalError ee ) {
138                                    // Ease debugging...
139                                    // XThis.this refers to the enclosing class instance
140                                    if ( Interpreter.DEBUG ) 
141                                            Interpreter.debug( "EvalError in scripted interface: "
142                                            + XThis.this.toString() + ": "+ ee );
143                                    throw ee;
144                            }
145                    }
146    
147                    public Object invokeImpl( Object proxy, Method method, Object[] args ) 
148                            throws EvalError 
149                    {
150                            String methodName = method.getName();
151                            CallStack callstack = new CallStack( namespace );
152    
153                            /*
154                                    If equals() is not explicitly defined we must override the 
155                                    default implemented by the This object protocol for scripted
156                                    object.  To support XThis equals() must test for equality with 
157                                    the generated proxy object, not the scripted bsh This object;
158                                    otherwise callers from outside in Java will not see a the 
159                                    proxy object as equal to itself.
160                            */
161                            BshMethod equalsMethod = null;
162                            try {
163                                    equalsMethod = namespace.getMethod( 
164                                            "equals", new Class [] { Object.class } );
165                            } catch ( UtilEvalError e ) {/*leave null*/ }
166                            if ( methodName.equals("equals" ) && equalsMethod == null ) {
167                                    Object obj = args[0];
168                                    return new Boolean( proxy == obj );
169                            }
170    
171                            /*
172                                    If toString() is not explicitly defined override the default 
173                                    to show the proxy interfaces.
174                            */
175                            BshMethod toStringMethod = null;
176                            try {
177                                    toStringMethod = 
178                                            namespace.getMethod( "toString", new Class [] { } );
179                            } catch ( UtilEvalError e ) {/*leave null*/ }
180    
181                            if ( methodName.equals("toString" ) && toStringMethod == null)
182                            {
183                                    Class [] ints = proxy.getClass().getInterfaces();
184                                    // XThis.this refers to the enclosing class instance
185                                    StringBuffer sb = new StringBuffer( 
186                                            XThis.this.toString() + "\nimplements:" );
187                                    for(int i=0; i<ints.length; i++)
188                                            sb.append( " "+ ints[i].getName() 
189                                                    + ((ints.length > 1)?",":"") );
190                                    return sb.toString();
191                            }
192    
193                            Class [] paramTypes = method.getParameterTypes();
194                            return Primitive.unwrap( 
195                                    invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) );
196                    }
197            };
198    }
199    
200    
201