/src/bsh/This.java

http://beanshell2.googlecode.com/ · Java · 453 lines · 204 code · 42 blank · 207 comment · 45 complexity · a3ed64aa9fbd29bc80a20d3bb8e70559 MD5 · raw file

  1. /*****************************************************************************
  2. * *
  3. * This file is part of the BeanShell Java Scripting distribution. *
  4. * Documentation and updates may be found at http://www.beanshell.org/ *
  5. * *
  6. * Sun Public License Notice: *
  7. * *
  8. * The contents of this file are subject to the Sun Public License Version *
  9. * 1.0 (the "License"); you may not use this file except in compliance with *
  10. * the License. A copy of the License is available at http://www.sun.com *
  11. * *
  12. * The Original Code is BeanShell. The Initial Developer of the Original *
  13. * Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
  14. * (C) 2000. All Rights Reserved. *
  15. * *
  16. * GNU Public License Notice: *
  17. * *
  18. * Alternatively, the contents of this file may be used under the terms of *
  19. * the GNU Lesser General Public License (the "LGPL"), in which case the *
  20. * provisions of LGPL are applicable instead of those above. If you wish to *
  21. * allow use of your version of this file only under the terms of the LGPL *
  22. * and not to allow others to use your version of this file under the SPL, *
  23. * indicate your decision by deleting the provisions above and replace *
  24. * them with the notice and other provisions required by the LGPL. If you *
  25. * do not delete the provisions above, a recipient may use your version of *
  26. * this file under either the SPL or the LGPL. *
  27. * *
  28. * Patrick Niemeyer (pat@pat.net) *
  29. * Author of Learning Java, O'Reilly & Associates *
  30. * http://www.pat.net/~pat/ *
  31. * *
  32. *****************************************************************************/
  33. package bsh;
  34. import java.io.IOException;
  35. import java.lang.reflect.*;
  36. import java.util.Map;
  37. import java.util.HashMap;
  38. /**
  39. 'This' is the type of bsh scripted objects.
  40. A 'This' object is a bsh scripted object context. It holds a namespace
  41. reference and implements event listeners and various other interfaces.
  42. This holds a reference to the declaring interpreter for callbacks from
  43. outside of bsh.
  44. */
  45. public final class This implements java.io.Serializable, Runnable
  46. {
  47. /**
  48. The namespace that this This reference wraps.
  49. */
  50. final NameSpace namespace;
  51. /**
  52. This is the interpreter running when the This ref was created.
  53. It's used as a default interpreter for callback through the This
  54. where there is no current interpreter instance
  55. e.g. interface proxy or event call backs from outside of bsh.
  56. */
  57. transient Interpreter declaringInterpreter;
  58. /**
  59. A cache of proxy interface handlers.
  60. Currently just one per interface.
  61. */
  62. private Map<Integer,Object> interfaces;
  63. private final InvocationHandler invocationHandler = new Handler();
  64. /**
  65. getThis() is a factory for bsh.This type references. The capabilities
  66. of ".this" references in bsh are version dependent up until jdk1.3.
  67. The version dependence was to support different default interface
  68. implementations. i.e. different sets of listener interfaces which
  69. scripted objects were capable of implementing. In jdk1.3 the
  70. reflection proxy mechanism was introduced which allowed us to
  71. implement arbitrary interfaces. This is fantastic.
  72. A This object is a thin layer over a namespace, comprising a bsh object
  73. context. We create it here only if needed for the namespace.
  74. Note: this method could be considered slow because of the way it
  75. dynamically factories objects. However I've also done tests where
  76. I hard-code the factory to return JThis and see no change in the
  77. rough test suite time. This references are also cached in NameSpace.
  78. */
  79. static This getThis(
  80. NameSpace namespace, Interpreter declaringInterpreter )
  81. {
  82. return new This( namespace, declaringInterpreter );
  83. }
  84. /**
  85. Get a version of this scripted object implementing the specified
  86. interface.
  87. */
  88. /**
  89. Get dynamic proxy for interface, caching those it creates.
  90. */
  91. public Object getInterface( Class clas )
  92. {
  93. return getInterface( new Class[] { clas } );
  94. }
  95. /**
  96. Get dynamic proxy for interface, caching those it creates.
  97. */
  98. public Object getInterface( Class [] ca )
  99. {
  100. if ( interfaces == null )
  101. interfaces = new HashMap<Integer,Object>();
  102. // Make a hash of the interface hashcodes in order to cache them
  103. int hash = 21;
  104. for(int i=0; i<ca.length; i++)
  105. hash *= ca[i].hashCode() + 3;
  106. Integer hashKey = new Integer(hash);
  107. Object interf = interfaces.get( hashKey );
  108. if ( interf == null )
  109. {
  110. ClassLoader classLoader = ca[0].getClassLoader(); // ?
  111. interf = Proxy.newProxyInstance(
  112. classLoader, ca, invocationHandler );
  113. interfaces.put( hashKey, interf );
  114. }
  115. return interf;
  116. }
  117. /**
  118. This is the invocation handler for the dynamic proxy.
  119. <p>
  120. Notes:
  121. Inner class for the invocation handler seems to shield this unavailable
  122. interface from JDK1.2 VM...
  123. I don't understand this. JThis works just fine even if those
  124. classes aren't there (doesn't it?) This class shouldn't be loaded
  125. if an XThis isn't instantiated in NameSpace.java, should it?
  126. */
  127. class Handler implements InvocationHandler, java.io.Serializable
  128. {
  129. public Object invoke( Object proxy, Method method, Object[] args )
  130. throws Throwable
  131. {
  132. try {
  133. return invokeImpl( proxy, method, args );
  134. } catch ( TargetError te ) {
  135. // Unwrap target exception. If the interface declares that
  136. // it throws the ex it will be delivered. If not it will be
  137. // wrapped in an UndeclaredThrowable
  138. // This isn't simple because unwrapping this loses all context info.
  139. // So rewrap is better than unwrap. - fschmidt
  140. Throwable t = te.getTarget();
  141. Class<? extends Throwable> c = t.getClass();
  142. String msg = t.getMessage();
  143. try {
  144. Throwable t2 = msg==null
  145. ? c.getConstructor().newInstance()
  146. : c.getConstructor(String.class).newInstance(msg)
  147. ;
  148. t2.initCause(te);
  149. throw t2;
  150. } catch(NoSuchMethodException e) {
  151. throw t;
  152. }
  153. } catch ( EvalError ee ) {
  154. // Ease debugging...
  155. // XThis.this refers to the enclosing class instance
  156. if ( Interpreter.DEBUG )
  157. Interpreter.debug( "EvalError in scripted interface: "
  158. + This.this.toString() + ": "+ ee );
  159. throw ee;
  160. }
  161. }
  162. public Object invokeImpl( Object proxy, Method method, Object[] args )
  163. throws EvalError
  164. {
  165. String methodName = method.getName();
  166. CallStack callstack = new CallStack( namespace );
  167. /*
  168. If equals() is not explicitly defined we must override the
  169. default implemented by the This object protocol for scripted
  170. object. To support XThis equals() must test for equality with
  171. the generated proxy object, not the scripted bsh This object;
  172. otherwise callers from outside in Java will not see a the
  173. proxy object as equal to itself.
  174. */
  175. BshMethod equalsMethod = null;
  176. try {
  177. equalsMethod = namespace.getMethod(
  178. "equals", new Class [] { Object.class } );
  179. } catch ( UtilEvalError e ) {/*leave null*/ }
  180. if ( methodName.equals("equals" ) && equalsMethod == null ) {
  181. Object obj = args[0];
  182. return proxy == obj;
  183. }
  184. /*
  185. If toString() is not explicitly defined override the default
  186. to show the proxy interfaces.
  187. */
  188. BshMethod toStringMethod = null;
  189. try {
  190. toStringMethod =
  191. namespace.getMethod( "toString", new Class [] { } );
  192. } catch ( UtilEvalError e ) {/*leave null*/ }
  193. if ( methodName.equals("toString" ) && toStringMethod == null)
  194. {
  195. Class [] ints = proxy.getClass().getInterfaces();
  196. // XThis.this refers to the enclosing class instance
  197. StringBuilder sb = new StringBuilder(
  198. This.this.toString() + "\nimplements:" );
  199. for(int i=0; i<ints.length; i++)
  200. sb.append( " "+ ints[i].getName()
  201. + ((ints.length > 1)?",":"") );
  202. return sb.toString();
  203. }
  204. Class [] paramTypes = method.getParameterTypes();
  205. return Primitive.unwrap(
  206. invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) );
  207. }
  208. }
  209. This( NameSpace namespace, Interpreter declaringInterpreter ) {
  210. this.namespace = namespace;
  211. this.declaringInterpreter = declaringInterpreter;
  212. //initCallStack( namespace );
  213. }
  214. public NameSpace getNameSpace() {
  215. return namespace;
  216. }
  217. public String toString() {
  218. return "'this' reference to Bsh object: " + namespace;
  219. }
  220. public void run() {
  221. try {
  222. invokeMethod( "run", new Object[0] );
  223. } catch( EvalError e ) {
  224. declaringInterpreter.error(
  225. "Exception in runnable:" + e );
  226. }
  227. }
  228. /**
  229. Invoke specified method as from outside java code, using the
  230. declaring interpreter and current namespace.
  231. The call stack will indicate that the method is being invoked from
  232. outside of bsh in native java code.
  233. Note: you must still wrap/unwrap args/return values using
  234. Primitive/Primitive.unwrap() for use outside of BeanShell.
  235. @see bsh.Primitive
  236. */
  237. public Object invokeMethod( String name, Object [] args )
  238. throws EvalError
  239. {
  240. // null callstack, one will be created for us
  241. return invokeMethod(
  242. name, args, null/*declaringInterpreter*/, null, null,
  243. false/*declaredOnly*/ );
  244. }
  245. /**
  246. Invoke a method in this namespace with the specified args,
  247. interpreter reference, callstack, and caller info.
  248. <p>
  249. Note: If you use this method outside of the bsh package and wish to
  250. use variables with primitive values you will have to wrap them using
  251. bsh.Primitive. Consider using This getInterface() to make a true Java
  252. interface for invoking your scripted methods.
  253. <p>
  254. This method also implements the default object protocol of toString(),
  255. hashCode() and equals() and the invoke() meta-method handling as a
  256. last resort.
  257. <p>
  258. Note: The invoke() meta-method will not catch the Object protocol
  259. methods (toString(), hashCode()...). If you want to override them you
  260. have to script them directly.
  261. <p>
  262. @param callstack if callStack is null a new CallStack will be created and
  263. initialized with this namespace.
  264. @param declaredOnly if true then only methods declared directly in the
  265. namespace will be visible - no inherited or imported methods will
  266. be visible.
  267. @see bsh.Primitive
  268. */
  269. /*
  270. invokeMethod() here is generally used by outside code to callback
  271. into the bsh interpreter. e.g. when we are acting as an interface
  272. for a scripted listener, etc. In this case there is no real call stack
  273. so we make a default one starting with the special JAVACODE namespace
  274. and our namespace as the next.
  275. */
  276. public Object invokeMethod(
  277. String methodName, Object [] args,
  278. Interpreter interpreter, CallStack callstack, SimpleNode callerInfo,
  279. boolean declaredOnly )
  280. throws EvalError
  281. {
  282. /*
  283. Wrap nulls.
  284. This is a bit of a cludge to address a deficiency in the class
  285. generator whereby it does not wrap nulls on method delegate. See
  286. Class Generator.java. If we fix that then we can remove this.
  287. (just have to generate the code there.)
  288. */
  289. if ( args == null ) {
  290. args = new Object[0];
  291. } else {
  292. Object [] oa = new Object [args.length];
  293. for(int i=0; i<args.length; i++)
  294. oa[i] = ( args[i] == null ? Primitive.NULL : args[i] );
  295. args = oa;
  296. }
  297. if ( interpreter == null )
  298. interpreter = declaringInterpreter;
  299. if ( callstack == null )
  300. callstack = new CallStack( namespace );
  301. if ( callerInfo == null )
  302. callerInfo = SimpleNode.JAVACODE;
  303. // Find the bsh method
  304. Class [] types = Types.getTypes( args );
  305. BshMethod bshMethod = null;
  306. try {
  307. bshMethod = namespace.getMethod( methodName, types, declaredOnly );
  308. } catch ( UtilEvalError e ) {
  309. // leave null
  310. }
  311. if ( bshMethod != null )
  312. return bshMethod.invoke( args, interpreter, callstack, callerInfo );
  313. /*
  314. No scripted method of that name.
  315. Implement the required part of the Object protocol:
  316. public int hashCode();
  317. public boolean equals(java.lang.Object);
  318. public java.lang.String toString();
  319. if these were not handled by scripted methods we must provide
  320. a default impl.
  321. */
  322. // a default toString() that shows the interfaces we implement
  323. if ( methodName.equals("toString") && args.length==0 )
  324. return toString();
  325. // a default hashCode()
  326. if ( methodName.equals("hashCode") && args.length==0 )
  327. return new Integer(this.hashCode());
  328. // a default equals() testing for equality with the This reference
  329. if ( methodName.equals("equals") && args.length==1 ) {
  330. Object obj = args[0];
  331. return new Boolean( this == obj );
  332. }
  333. // a default clone()
  334. if ( methodName.equals("clone") && args.length==0 ) {
  335. NameSpace ns = new NameSpace(namespace,namespace.getName()+" clone");
  336. try {
  337. for( String varName : namespace.getVariableNames() ) {
  338. ns.setLocalVariable(varName,namespace.getVariable(varName,false),false);
  339. }
  340. for( BshMethod method : namespace.getMethods() ) {
  341. ns.setMethod(method);
  342. }
  343. } catch ( UtilEvalError e ) {
  344. throw e.toEvalError( SimpleNode.JAVACODE, callstack );
  345. }
  346. return ns.getThis(declaringInterpreter);
  347. }
  348. // Look for a default invoke() handler method in the namespace
  349. // Note: this code duplicates that in NameSpace getCommand()
  350. // is that ok?
  351. try {
  352. bshMethod = namespace.getMethod(
  353. "invoke", new Class [] { null, null } );
  354. } catch ( UtilEvalError e ) { /*leave null*/ }
  355. // Call script "invoke( String methodName, Object [] args );
  356. if ( bshMethod != null )
  357. return bshMethod.invoke( new Object [] { methodName, args },
  358. interpreter, callstack, callerInfo );
  359. throw new EvalError("Method " +
  360. StringUtil.methodString( methodName, types ) +
  361. " not found in bsh scripted object: "+ namespace.getName(),
  362. callerInfo, callstack );
  363. }
  364. /**
  365. Bind a This reference to a parent's namespace with the specified
  366. declaring interpreter. Also re-init the callstack. It's necessary
  367. to bind a This reference before it can be used after deserialization.
  368. This is used by the bsh load() command.
  369. <p>
  370. This is a static utility method because it's used by a bsh command
  371. bind() and the interpreter doesn't currently allow access to direct
  372. methods of This objects (small hack)
  373. */
  374. public static void bind(
  375. This ths, NameSpace namespace, Interpreter declaringInterpreter )
  376. {
  377. ths.namespace.setParent( namespace );
  378. ths.declaringInterpreter = declaringInterpreter;
  379. }
  380. /**
  381. Allow invocations of these method names on This type objects.
  382. Don't give bsh.This a chance to override their behavior.
  383. <p>
  384. If the method is passed here the invocation will actually happen on
  385. the bsh.This object via the regular reflective method invocation
  386. mechanism. If not, then the method is evaluated by bsh.This itself
  387. as a scripted method call.
  388. */
  389. static boolean isExposedThisMethod( String name )
  390. {
  391. return
  392. name.equals("getClass")
  393. || name.equals("invokeMethod")
  394. || name.equals("getInterface")
  395. // These are necessary to let us test synchronization from scripts
  396. || name.equals("wait")
  397. || name.equals("notify")
  398. || name.equals("notifyAll");
  399. }
  400. }